Question

here it is my code:

...
setContentView(R.layout.activity_main);
        myGrid= (GridLayout) findViewById(R.id.gridlayout);
        myGrid.setColumnCount(3);
        myGrid.setRowCount(5);

        ImageButton a1 = new ImageButton(this);
    ImageButton a2 = new ImageButton(this);
    myGrid.addView(a1);
    myGrid.addView(a2);
    a1.setOnClickListener(this);
    a2.setOnClickListener(this);
...

What I need to write in onClick method? I want that if I press button "a1" it will do something and if I press button "a2" it will do something another.

public void onClick(View a) {


 I can't use "if (a.getId == buttonID)" , because my buttons haven't ID.
    }

In simple Java it was like if((a.getSource() == button1)), but I don't know how it looks in Android.

Was it helpful?

Solution

In Android, you need to override onClick method in the listener:

a1.setOnClickListener(new OnClickListener(){
   @Override
   public void onClick(View view){
       // do something
   }

});

Or create a custom listener one for both buttons, where you will check which view was clicked:

myOnClickListener = new OnClickListener(){
    @Override
    public void onClick(View view){
        if (view == a1){
           // do what a1 should do
        } else if (view == a2) {
           // do what a2 should do
        }
    }
};

and append it to both buttons:

a1.setOnClickListener(myOnClickListener);
a2.setOnClickListener(myOnClickListener);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top