Umair Umair - 1 year ago 65
Android Question

Can we get onClickListener functionality of buttons defined in Layout from onOptionsItemSelected() click

This is the most simplified version in which I could entitled my question.

Problem: Suppose two buttons are working fine with their functionality in an Activity. What i want is that if we click an item from menu items, how could we (if possible) integrate it one of the the buttons onClickListener so that it would perform the same functionality as one of those buttons are performing already.

Scenario: Lets assume we have two buttons in XML files implementing onCLickListener interface. While clicking the menu item, the inner class constructor has been initialized but it doesn't go further which makes sense. Can anyone guide me what are the options here to work with the logic I want to embed here.

cameraButton.setOnClickListener(new MyButtonClickListener(MyConstants.OPEN_CAMERA));
mediaButton.setOnClickListener(new MyButtonClickListener(MyConstants.OPEN_MEDIA));

where MyButtonClickListener is an inner class

private class MyButtonClickListener implements View.OnClickListener {

private int preference;

public MyButtonClickListener(int preference) {
this.preference = preference;
Log.e("Pref in Constructor:", String.valueOf(preference));


public MyButtonClickListener() {

public void onClick(View v) {
Log.e("Pref in onClick:", String.valueOf(preference));

and the method startScan is :

public void startScan(int preference) {
Log.e("Pref: StartScan Method:", String.valueOf(preference));

Intent intent = new Intent(this, MyActivity.class);
intent.putExtra(MyConstants.OPEN_INTENT_PREFERENCE, preference);
startActivityForResult(intent, REQUEST_CODE);


public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {

new MyButtonClickListener(MyConstants.OPEN_MEDIA);
//return true;

Answer Source

As your startScan() method belongs to your activity/fragment class, you can call it directly in the required case block of your onOptionsItemSelected() method. You do not need to go via an interface for that.