adding click listener to titlebar image

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-14 08:49:06

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/14033204/adding-click-listener-to-titlebar-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!