Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" :)

like image 205
paul smith Avatar asked Dec 25 '12 18:12

paul smith


2 Answers

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.

like image 90
A--C Avatar answered Nov 06 '22 11:11

A--C


You should use the ActionBar. Use ActionBarSherlock to have it also for Android versions less than 3.0. To make the Icon clickable, see the ActionBar API Docs (see link below). It's very easy, you just activate the behaviour and then it works like a menu-item with a special item-id.

  • http://developer.android.com/guide/topics/ui/actionbar.html#Home
like image 37
Ridcully Avatar answered Nov 06 '22 09:11

Ridcully