java - Findviewbyid 找不到按钮

标签 java android

我是 Android 编程新手,所以我有一个简单的问题! 我在 activity_main.xmlmain_activity.java 中创建了一个 button 我想通过调用 findbyviewid() 使用此按钮code> 但当我编写它时,它在 activity_main.xml 中找不到我的按钮! 这是代码: 包 com.example.test;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b=findViewById(R.layout.button1);//this is where i get error message that can't find my button

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

那么我的问题是什么?

谢谢!!!

最佳答案

试试这个:

Button btn = (Button)findViewById(R.id.button);

findViewById 将返回一个 View 对象,您必须将其向下转换为 Button 对象。

关于java - Findviewbyid 找不到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452761/

相关文章:

java - ExecutorService 和 Runnable

java - 使用数组时处理空指针的干净方法

java - JAXB 与 Apache XMLBeans

android - 以编程方式在 edittext 下方创建一个新的 textview

android - 我缺少一些 Dagger 基础知识 [CoffeeMaker App 示例]

android - 检测 ValueAnimator 何时完成

java - 使用 Java I/O 通过 HTTP 网络读取流

android - 为什么 flutter apk 文件大小稍大

android - 通知并不总是通过电话收到?

java - 是否可以使用 iBATIS 中止长时间运行的查询?