I have MainMenu. There’s 3 different ImageButtons for starting new Activities. Everything work fine, but I wondering is possible another way to code this. I took this from example code with one button, and I think its not look good: setting new OnClickListener() for each button.
public class MainMenu extends Activity implements OnClickListener{
ImageButton firstModule;
ImageButton secondModule;
ImageButton thirdModule;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
//init buttons
firstModule = (ImageButton) findViewById(R.id.imageButton1);
secondModule = (ImageButton) findViewById(R.id.imageButton2);
thirdModule = (ImageButton) findViewById(R.id.imageButton3);
firstModule.setOnClickListener(this);
secondModule.setOnClickListener(this);
thirdModule.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
startActivity(new Intent(MainMenu.this, BasicFunctions.class));
break;
case R.id.imageButton2:
startActivity(new Intent(MainMenu.this, GpsModule.class));
break;
case R.id.imageButton3:
startActivity(new Intent(MainMenu.this, Graphic3D.class));
break;
}
}
}
The more elegant way is to implement
View.OnClickListenerinside yourActivityand then process clicks inside theonClick()method of yourActivity. It gives you aViewobject as an argument, you can retrieve the view’s id using theview.getId()method, then you can use theswitchblock to implement actions for everyButtonin your layout. Hope this helps.