2015-02-10 89 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

相關問題