Android OnClickListener - identify a button

AndroidEventsResourcesListener

Android Problem Overview


I have the activity:

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler);
    b2.setOnClickListener(myhandler);
    ...
  }
  View.OnClickListener myhandler = new View.OnClickListener() {
    public void onClick(View v) {
      // MY QUESTION STARTS HERE!!!
      // IF b1 do this
      // IF b2 do this
      // MY QUESTION ENDS HERE!!!
    }
  }
}

How do I check which button has been clicked?

Android Solutions


Solution 1 - Android

You will learn the way to do it, in an easy way, is:

public class Mtest extends Activity {
  Button b1;
  Button b2;
  public void onCreate(Bundle savedInstanceState) {
    ...
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(myhandler1);
    b2.setOnClickListener(myhandler2);
    ...
  }
  View.OnClickListener myhandler1 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 1st button
    }
  };
  View.OnClickListener myhandler2 = new View.OnClickListener() {
    public void onClick(View v) {
      // it was the 2nd button
    }
  };
}

Or, if you are working with just one clicklistener, you can do:

View.OnClickListener myOnlyhandler = new View.OnClickListener() {
  public void onClick(View v) {
      switch(v.getId()) {
        case R.id.b1:
          // it was the first button
          break;
        case R.id.b2:
          // it was the second button
          break;
      }
  }
}

Though, I don't recommend doing it that way since you will have to add an if for each button you use. That's hard to maintain.

Solution 2 - Android

Or you can try the same but without listeners. On your button XML definition:

android:onClick="ButtonOnClick"

And in your code define the method ButtonOnClick:

public void ButtonOnClick(View v) {
    switch (v.getId()) {
      case R.id.button1:
        doSomething1();
        break;
      case R.id.button2:
        doSomething2();
        break;
      }
}

Solution 3 - Android

I prefer:

class MTest extends Activity implements OnClickListener {
    public void onCreate(Bundle savedInstanceState) {
    ...
    Button b1 = (Button) findViewById(R.id.b1);
    Button b2 = (Button) findViewById(R.id.b2);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    ...
}

And then:

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.b1:
            ....
            break;
        case R.id.b2:
            ....
            break;
    }	
}

Switch-case is easier to maintain than if-else, and this implementation doesn't require making many class variables.

Solution 4 - Android

Five Ways to Wire Up an Event Listener is a great article overviewing the various ways to set up a single event listener. Let me expand that here for multiple listeners.

  1. Member Class

public class main extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //attach an instance of HandleClick to the Button
        HandleClick handleClick = new HandleClick();
        findViewById(R.id.button1).setOnClickListener(handleClick);
        findViewById(R.id.button2).setOnClickListener(handleClick);
    }    
    private class HandleClick implements OnClickListener{
        public void onClick(View view) {
	        switch(view.getId()) {
	        case R.id.button1:
	            // do stuff
	            break;
	        case R.id.button2:
	            // do stuff
	            break;
	        }
	    }
    }
}

2. Interface Type

public class main extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViewById(R.id.button1).setOnClickListener(handleClick);
		findViewById(R.id.button2).setOnClickListener(handleClick);
	}
	private OnClickListener handleClick = new OnClickListener() {
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.button1:
				// do stuff
				break;
			case R.id.button2:
				// do stuff
				break;
			}
		}
	};
}

3. Anonymous Inner Class

public class main extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				// do stuff
			}
		});
		findViewById(R.id.button2).setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				// do stuff
			}
		});
	}
}

4. Implementation in Activity

public class main extends Activity implements OnClickListener {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViewById(R.id.button1).setOnClickListener(this);
		findViewById(R.id.button2).setOnClickListener(this);
	}
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.button1:
			// do stuff
			break;
		case R.id.button2:
			// do stuff
			break;
		}
	}
}

5. Attribute in View Layout for OnClick Events

public class main extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
	public void HandleClick(View view) {
		switch (view.getId()) {
		case R.id.button1:
			// do stuff
			break;
		case R.id.button2:
			// do stuff
			break;
		}
	}
}

And in xml:

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="HandleClick" />
<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="HandleClick" />

Solution 5 - Android

Another way of doing it is a single listener from activity , like this:

public class MyActivity extends Activity implements OnClickListener {
    .......  code
    
    //my listener
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.mybutton) { 
            DoSomething();
            return;
        }
 
        if (v.getId() == R.id.mybutton2) { 
            DoSomething2();
            return;
        }
    }
}

I Like to do it with single IF instead of switch-else, but if you prefer that, then you should do:

//my listener
@Override
public void onClick(View v) {
    switch(v.getId()) {
        case R.id.mybutton:
        { 
             DoSomething();
             break;
        }
   
        case R.id.mybutton2:
        {
            DoSomething();
            break;
        }
    }
}

Solution 6 - Android

If you don't want to save instances of the 2 button in the class code, follow this BETTER way (this is more clear and fast!!) :

public void buttonPress(View v) {
  switch (v.getId()) {
    case R.id.button_one:
        // do something
        break;
    case R.id.button_two:
        // do something else
        break;
    case R.id.button_three:
        // i'm lazy, do nothing
        break;
  }
}

Solution 7 - Android

The best way is by switch-ing between v.getId(). Having separate anonymous OnClickListener for each Button is taking up more memory. Casting View to Button is unnecessary. Using if-else when switch is possible is slower and harder to read. In Android's source you can often notice comparing the references by if-else:

if (b1 == v) {
 // ...
} else if (b2 == v) {

I don't know exactly why they chose this way, but it works too.

Solution 8 - Android

use setTag();

like this:

@Override    
public void onClick(View v) {     
    int tag = (Integer) v.getTag();     
    switch (tag) {     
    case 1:     
        System.out.println("button1 click");     
        break;     
    case 2:     
        System.out.println("button2 click");     
       break;   
    }     
}     

Solution 9 - Android

In addition to Cristian C's answer (sorry, I do not have the ability to make comments), if you make one handler for both buttons, you may directly compare v to b1 and b2, or if you want to compare by the ID, you do not need to cast v to Button (View has getId() method, too), and that way there is no worry of cast exception.

Solution 10 - Android

Button mybutton = new Button(ViewPagerSample.this);
mybutton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
			// TODO Auto-generated method stub
    }
});

Solution 11 - Android

Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);

@Override
public void onClick(View v) {
	// TODO Auto-generated method stub
	if(v.getId() == R.id.button1){
		Toast.makeText(context, "Button 1 Click", Toast.LENGTH_LONG).show();
	}
}

Check this article for more details

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxpepermintView Question on Stackoverflow
Solution 1 - AndroidCristianView Answer on Stackoverflow
Solution 2 - AndroidChronosView Answer on Stackoverflow
Solution 3 - AndroidSaad FarooqView Answer on Stackoverflow
Solution 4 - AndroidSuragchView Answer on Stackoverflow
Solution 5 - AndroidruhaldeView Answer on Stackoverflow
Solution 6 - Androidlory105View Answer on Stackoverflow
Solution 7 - AndroidognianView Answer on Stackoverflow
Solution 8 - Androiduser2644305View Answer on Stackoverflow
Solution 9 - AndroidDonSteepView Answer on Stackoverflow
Solution 10 - AndroidTai NguyenView Answer on Stackoverflow
Solution 11 - Androiduser7925882View Answer on Stackoverflow