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.OnClickListener
inside your Activity
and then process clicks inside the onClick()
method of your Activity
. It gives you a View
object as an argument, you can retrieve the view's id using the view.getId()
method, then you can use the switch
block to implement actions for every Button
in your layout. Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.