2013-12-08 59 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);