java - 错误 : incompatible types: View cannot be converted to Button

标签 java android compiler-errors

这段代码有问题:

{
    TextView txt;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt=(TextView) findViewById(R.id.mytext);
        btn=(Button) findViewById(R.id.mybutton);

        btn.setOnClickListener (new View.OnClickListener(){
            @Override
            public void onClick(View V){
                txt.setText("TAK");
            }
        });
}

结果,我收到错误信息:

incompatible types: View cannot be converted to Button

我做错了什么?

最佳答案

检查您的 Activity 的 xml 文件,mybutton 应该是另一个 View 组件。

您的 xml View 按钮应该是这样的:

<Button
   android:text="Button"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:id="@+id/mybutton" />

检查是否不是 ImageButton 或 ToggleButton。

关于java - 错误 : incompatible types: View cannot be converted to Button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53161658/

相关文章:

java - 如何检查一个ArrayList的元素是否都包含在另一个ArrayList中

C#:检查类型 T 是否为 bool

python-3.x - 无法在生命周期内导入估计模块

java - 模拟静态方法

Java <-> 非 Applets 的 Javascript?

java - ListView 上的弹出上下文菜单保持

Android - Seekbar 自定义进度缩放

java - Android Facebook key 哈希—— "remote_app_id does not match stored id"

c++ - Dev C++中的嵌入式SQL

Java 使用 .jar 文件中的图像