我有一个名为MainActivity的活动,它有两个布局。上一个活动有两个按钮可以选择要设置的布局。我需要MainActivity中的按钮根据使用的布局采取不同的行为,这是我的代码:< / p>
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;
}
}
答案 0 :(得分: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
}