0

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

运行应用程序时它会崩溃。请有人可以帮助我

4

2 回答 2

5

实际上,您在定义之前忘记setContentView(R.layout.<main_xml>);onCreate()Activity 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

于 2012-11-28T13:23:51.397 回答
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();
                    }
           });
 }
}
于 2012-11-28T13:28:01.830 回答