获取工具栏的导航图标视图参考 [英] Get Toolbar's navigation icon view reference
本文介绍了获取工具栏的导航图标视图参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的Toolbar
中突出显示抽屉图标(正在使用教程).为此,我需要它的位置.如何获得对抽屉导航图标(汉堡包)视图的引用?
I would like to highlight drawer icon in my Toolbar
(working on a tutorial). For that, I need its position. How do I get a reference to drawer's navigation icon (hamburger) view?
推荐答案
您可以使用视图的内容描述,然后使用findViewWithText()
方法获取视图引用
You can make use of content description of the view and then use findViewWithText()
method to get view reference
public static View getToolbarNavigationIcon(Toolbar toolbar){
//check if contentDescription previously was set
boolean hadContentDescription = !TextUtils.isEmpty(toolbar.getNavigationContentDescription());
String contentDescription = hadContentDescription ? toolbar.getNavigationContentDescription() : "navigationIcon";
toolbar.setNavigationContentDescription(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 setNavigationContentDescription ensures its existence
View navIcon = null;
if(potentialViews.size() > 0){
navIcon = potentialViews.get(0); //navigation icon is ImageButton
}
//Clear content description if not previously present
if(!hadContentDescription)
toolbar.setNavigationContentDescription(null);
return navIcon;
}
Kotlin扩展属性:
Kotlin extension property:
val Toolbar.navigationIconView: View?
get() {
//check if contentDescription previously was set
val hadContentDescription = !TextUtils.isEmpty(navigationContentDescription)
val contentDescription = if (hadContentDescription) navigationContentDescription else "navigationIcon"
navigationContentDescription = contentDescription
val potentialViews = arrayListOf<View>()
//find the view based on it's content description, set programatically or with android:contentDescription
findViewsWithText(potentialViews, contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION)
//Clear content description if not previously present
if (!hadContentDescription) {
navigationContentDescription = null
}
//Nav icon is always instantiated at this point because calling setNavigationContentDescription ensures its existence
return potentialViews.firstOrNull()
}
这篇关于获取工具栏的导航图标视图参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文