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

前端之家收集整理的这篇文章主要介绍了android – 工具栏的徽标图标是否可点击?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经使用了工具栏所以现在我想在徽标图标上应用点击事件我怎么能得到这个事件?

这是我做过的一些编码

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

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

解决方法

你需要首先参考它
View logoView = getToolbarlogoView(toolbar);
logoView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //logo clicked
    }
});

使用内容描述我们可以获得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;
    }
原文链接:https://www.f2er.com/android/314387.html

猜你在找的Android相关文章