1

我有一个名为 MainActivity 的活动,它有两个布局。前一个活动有两个按钮来选择要设置的布局。我需要 MainActivity 中的按钮根据使用的布局做出不同的行为,这是我的代码:

    public class MainActivity extends Activity implements OnClickListener {

        Button shoot;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
         int btnNumber = extras.getInt("button");
         switch(btnNumber) 
         {
           case 1 : setContentView(R.layout.first_layout); break;
           case 2 : setContentView(R.layout.second_layout); break;
         }
      }


      shoot=(Button)findViewById(R.id.button1);
        shoot.setOnClickListener(this);


        public void onClick(View arg0) {
        // TODO Auto-generated method stub

        switch(arg0.getId()) {


        case R.id.button1:


                    // WHAT SHOULD THE CODE BE HERE

                    break;

    }


}
4

1 回答 1

0

编辑您的代码以在顶部有一个私有变量

private int whichLayout = 0;

然后,当您获得捆绑包时,请执行以下操作:

     switch(btnNumber) 
     {
       case 1 : setContentView(R.layout.first_layout); whichLayout = 1; break;
       case 2 : setContentView(R.layout.second_layout); whichLayout = 2; break;
       default: //Handle this
     }

最后像这样编辑你的 onClick 监听器:

public void onClick(View arg0) {

    switch(whichLayout) {
    case 1: {//Do what you want; } break;
    case 2: {//Do what you want; } break;
    default: //Handle this
}
于 2013-07-13T21:36:25.540 回答