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" :)
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 ActionBar
s, only classic window title bars.
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