Reputation: 559
i'm able to open 1 new activity(layout) with 1 button click but, I want to open 4 different activities(layouts) with 4 different buttons clicks from main page. I tried switch but failed.
Upvotes: 0
Views: 93
Reputation: 3906
you button click listener..
but1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
open(v);
}
});
repeat this for all button
create method to open other activity
public void open(View v){
Intent intent = null;
switch (v.getId()) {
case R.id.but1: // your button id
intent = new Intent(Activity1.this,Activity2.class);
break;
// -- so on
}
startActivity(intent);
finish();
}
place all your activity intent in 2,3,4 case..
Upvotes: 0
Reputation: 2509
You need to implement View.OnClickListener
in your MainActivity
and in onClick
method do this:
@Override
public void onClick(View v) {
Intent intent;
switch(v.getId()){
case R.id.btn_1:
intent = new Intent(MainActivity.this,YourClass1.class);
startActivity(intent);
break;
case R.id.bt_2:
intent = new Intent(MainActivity.this,YourClass2.class);
startActivity(intent);
break;
case R.id.bt_3:
intent = new Intent(MainActivity.this,YourClass3.class);
startActivity(intent);
break;
case R.id.bt_4:
intent = new Intent(MainActivity.this,YourClass4.class);
startActivity(intent);
break;
}
}
and in you onCreate()
method in MainActivity
must set clickListener to evry button
like this :
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1= (Button) findViewById(R.id.bt_1);
btn2= (Button) findViewById(R.id.bt_2);
btn3= (Button) findViewById(R.id.bt_3);
btn4= (Button) findViewById(R.id.bt_4);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
}
Upvotes: 0
Reputation: 928
try this:
In button declaration:
btn1= (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(click);
btn2= (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(click);
btn3= (Button) findViewById(R.id.btn3);
btn3.setOnClickListener(click);
btn4= (Button) findViewById(R.id.btn4);
btn4.setOnClickListener(click);
and the listener ...
View.OnClickListener click= new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn1:
activity1();
break;
case R.id.btn2:
activity2();
break;
case R.id.btn3:
activity3();
break;
case R.id.btn4:
activity4();
break;
}
}
};
Upvotes: 1