Search code examples
androidandroid-activitytitlebar

adding click listener to titlebar image


Merry Christmas and Happy Holidays everyone!

I'm trying to setup a listener on the image icon that appears on the left side of the default title bar, but so far not having any luck.

Here's my Activity's onCreate:

@Override public void onCreate(Bundle savedInstanceState) {
   requestWindowFeature(Window.FEATURE_LEFT_ICON);
   super.onCreate(savedInstanceState);
   findViewById(Window.FEATURE_LEFT_ICON).setOnClickListener(new OnClickListener() {
       @Override public void onClick(View v) {
           System.out.println("It works!");
       }
   });
}

Any suggestions? I'm hoping to not see the answer "it's not possible" :)


Solution

  • There doesn't seem to be an id for the left icon, however for the classic title bar, there is an id available: android.R.id.title Here is a sample Activity using this id. The requestWindowFeature(Window.FEATURE_LEFT_ICON); should force the classic title bar regardless of theme.

    public class MainActivity extends Activity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_LEFT_ICON);
        setContentView(R.layout.activity_main);
        getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.ic_launcher);
        View v = findViewById (android.R.id.title);
        v.setClickable(true);
        v.setOnClickListener(new OnClickListener() {
            @Override public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Works!", Toast.LENGTH_SHORT).show();
            }
        });
    }
    }
    

    Basically, what this does, is it finds the id of the title bar (android.R.id.title) then assigns an onClickListener to it.

    This will not work with ActionBars, only classic window title bars.