增加点击监听器标题栏的图片监听器、标题栏、图片

2023-09-12 23:45:12 作者:06年的戒指

圣诞节日快乐大家!

我试图安装上默认的标题栏的左侧显示的图像图标上的监听器,但到目前为止还没有任何运气。

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.

下面是我的活动的onCreate:

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

推荐答案

似乎没有成为一个ID为左侧的图标,但对于经典的标题栏,有一个号: android.R.id.title 下面是一个使用该ID的示例活动。该 requestWindowFeature(Window.FEATURE_LEFT_ICON); 应该强制主题的经典标题栏,无论

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();
        }
    });
}
}

基本上,这是什么呢,是它发现了标题栏的ID( android.R.id.title ),然后分配一个 onClickListener 给它。

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

这将不可以与动作条 S,只有经典的窗口标题栏的工作。

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