2013-12-08 110 views
0

我在android編程中很新,所以我有一點點簡單的問題! 我activity_main.xml創建buttonmain_activity.java我想通過調用findbyviewid()使用此按鈕,但是當我寫它,它無法找到我的activity_main.xml!這個按鈕是代碼: 包com.example.test;Findviewby ID找不到按鈕

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

} 

那麼我的問題是什麼?

謝謝!!!

回答

4

試試這個:

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

findViewById會返回一個視圖對象,你必須將它下載到Button對象中。

1

您需要在佈局中查找按鈕的ID。

Button b=(Button)findViewById(R.id.button1); 

假設你的佈局activity_main包含:

<Button 
    android:id="@+id/button1" 
    /*****/ 
/> 

你會發現這個tutorial有用。

0

其類型強制轉換爲Button類第一,它應該是R.id.button1代替R.layout.button1

Button b=(Button)findViewById(R.id.button1) 
+0

'R.layout.button1' ?? – Raghunandan

0

Chanage到

Button b=(Button) findViewById(R.id.button1);