2015-02-10 91 views
1

我有一个按钮创建一个Android应用程序,和我的XML看起来像这样:的Android无法找到XML项目

<Button 
    android:id="@+id/start" 
    android:text="Start" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 

然后,我想要得到的按钮在我的主类,但我不能。

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); 

但我最肯定确定按钮。任何人都可以解释为什么这不起作用?

+0

欢迎来到SO!你有一个很好的问题,所以+1。但在将来适用时,请在您的帖子中包含错误/例外/ logcat输出。我相信你现在已经从@ThalluimPig得到了答案,但是你仍然可以将错误消息添加到你的帖子中,以帮助未来的用户解决同样的问题。 – codeMagic 2015-02-10 00:43:46

回答

2

方法findViewById()返回View。你需要把它作为Button

start = (Button) findViewById(R.id.start); 
+0

感谢您添加解释而不仅仅是代码。整个社区对此表示赞赏+1 :) – codeMagic 2015-02-10 00:46:09

相关问题