我正在创建一个带有按钮的 android 应用程序,我的 xml 如下所示:
<Button
android:id="@+id/start"
android:text="Start"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
然后我想在我的主类中获取 Button,但我不能。
Button start;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
start = findViewById(R.id.start);
}
但是当我这样做时,应用程序不会运行,因为这一行有错误:
start = findViewById(R.id.start);
但我绝对确定了 Button。谁能解释为什么这不起作用?
最佳答案
findViewById()
方法返回一个 View
。您需要将其转换为 Button
。
start = (Button) findViewById(R.id.start);
关于Android 找不到 xml 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28422147/