工具栏的徽标图标是否可点击?

Raj*_*jan 6 android toolbar android-actionbar android-5.0-lollipop

我已经使用了工具栏所以现在我想在徽标图标上应用点击事件我怎么能得到这个事件?

这是我做过的一些编码

Toolbar toolbar = null;
toolbar = (Toolbar) findViewById(R.id.actionToolbar);
setSupportActionBar(toolbar);
setTitle(null);
toolbar.setNavigationIcon(R.drawable.back);
toolbar.setNavigationContentDescription("BACK");
toolbar.setLogo(R.drawable.ic_launcher);
toolbar.setLogoDescription("LOGO");

toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Nav", Toast.LENGTH_SHORT).show();
    }
});
Run Code Online (Sandbox Code Playgroud)

在这里,我设置了导航图标和徽标图标,所以现在我想要logo图标的点击事件,怎么可能?

Nik*_*ski 22

你需要首先参考它

View logoView = getToolbarLogoView(toolbar);
logoView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //logo clicked
    }
});
Run Code Online (Sandbox Code Playgroud)

使用内容描述我们可以View参考.请参阅内联评论.

public static View getToolbarLogoIcon(Toolbar toolbar){
        //check if contentDescription previously was set
        boolean hadContentDescription = android.text.TextUtils.isEmpty(toolbar.getLogoDescription());
        String contentDescription = String.valueOf(!hadContentDescription ? toolbar.getLogoDescription() : "logoContentDescription");
        toolbar.setLogoDescription(contentDescription);
        ArrayList<View> potentialViews = new ArrayList<View>();
        //find the view based on it's content description, set programatically or with android:contentDescription
        toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
        //Nav icon is always instantiated at this point because calling setLogoDescription ensures its existence 
        View logoIcon = null;
        if(potentialViews.size() > 0){
            logoIcon = potentialViews.get(0);
        }
        //Clear content description if not previously present
        if(hadContentDescription)
            toolbar.setLogoDescription(null);
        return logoIcon;
    }
Run Code Online (Sandbox Code Playgroud)


Min*_*eng 11

我问自己同样的问题并且遇到了这个问题.我对Nikola Despotoski采取了类似的方法,但采用了不同的实现方式.

而不是方法,我做的是:

// Set drawable
toolbar.setLogo(ContextCompat.getDrawable(context, R.drawable.logo));

// Find logo
View view = toolbar.getChildAt(1);
view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      // Perform actions
    }
  });
Run Code Online (Sandbox Code Playgroud)

稍微破解,但稍后会再回顾一下.分享用于讨论目的.

  • 感谢那.对我来说,孩子(0)是标志.孩子1是标题 (2认同)