iniciar nuevas actividades desde ImageButtons

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 nuevo OnClickListener () para cada botón.

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;
    }

}

}

preguntado el 02 de septiembre de 12 a las 23:09

1 Respuestas

The more elegant way is to implement View.OnClickListener dentro de su Activity and then process clicks inside the onClick() método de su Activity. Te da un View object as an argument, you can retrieve the view's id using the view.getId() método, entonces puede usar el switch block to implement actions for every Button in your layout. Hope this helps.

Respondido el 02 de Septiembre de 12 a las 23:09

I tried Your solution (first post edited) but buttons are not react on clicking. I have no Idea for now. - mariusz chw

I made a breakpoint in switch() and it's seems the method OnClic() is never used. - mariusz chw

I forgot to set onClickListener for each button, post edited. Thanks a lot for help Egor! - mariusz chw

@MariuszChw, You're welcome! Sorry, I wasn't able to answer on your comments, but I'm glad you've got it going. - Egor

I think that the way You explain me what to do with it, it's the best method for newbie programmers. You didn't paste me final code. I got explanation what should I do, it forced me to start thinking, to understand mechanism of this operation. Thanks a lot again - mariusz chw

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.