应用程序在设置两个onclick侦听器时崩溃

时间:2012-11-28 13:22:54

标签: android

我已将以下代码放在onCreate方法的主要活动中

public class MyTest extends Activity implements OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 //... some other code here to init the layout
    Button btn1 = (Button)findViewById(R.id.button1);
    Button btn2 = (Button)findViewById(R.id.button2);
    btn1.setOnClickListener(this);
    btn2.setOnClickListener(this);
}

并将以下代码放在MyTest类

之外
@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.button1:
            break;
        case R.id.button2:
            break;
    }
}

运行应用程序时崩溃。请有人帮帮我

2 个答案:

答案 0 :(得分:5)

实际上,在定义setContentView(R.layout.<main_xml>);之前,您已在活动的onCreate()中忘记了Buttons

类似的东西,

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.<main_xml>); // This line is necessary
 .
 .
 .

更新

另外你必须把

@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.button1:
            break;
        case R.id.button2:
            break;
    }
}
作为onCreate()的一部分,在MyTest Activity Class方法之外

。不在MyTest Activity Class之外。

答案 1 :(得分:0)

public class MyTest extends Activity implements OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.main_xml);
    Button btn1 = (Button)findViewById(R.id.button1);
    Button btn2 = (Button)findViewById(R.id.button2); 

    btn1.setOnClickListener(new OnClickListener()
           {

                    public void onClick(View v) 
                    {
                           Toast.makeText(myactivity.this, "The button=1 was clicked.", Toast.LENGTH_LONG).show();
                    }
           });
    btn2.setOnClickListener(new OnClickListener()
           {

                    public void onClick(View v) 
                    {
                           Toast.makeText(myactivity.this, "The button=2 was clicked.", Toast.LENGTH_LONG).show();
                    }
           });
 }
}