Я хотел бы выделить значок ящика в моем Toolbar
(работаю над учебником). Для этого мне нужна его позиция. Как получить ссылку на значок навигации ящика (гамбургер)?
Получить ссылку на представление значка навигации панели инструментов
Ответы (4)
Вы можете использовать описание содержимого представления, а затем использовать метод findViewWithText()
для получения ссылки на представление.
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:
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()
}
toolbar.getNavigationIconView()
- person Singed; 30.04.2015
hadContentDescription
это true
, когда isEmpty
, кроме того, эта опечатка хорошо работает :)
- person snachmsm; 19.10.2018
Изучив дочерние представления панели инструментов в режиме отладки, я увидел, что значок ящика можно найти там как кнопку ImageButton. (Спасибо, Эллц)
Я использую панель инструментов с пользовательским макетом xml с двумя дочерними элементами (LinearLayout и ImageView), поэтому в конце у моей панели инструментов было 4 дочерних элемента со следующими позициями:
[0] LinearLayout(from custom xml)
[1] ImageView(from custom xml)
[2] ImageButton(drawer icon)
[3] ActionMenuView(menu icon)
Зная это, теперь я могу использовать:
View drawerIcon = toolbar.getChildAt(2);
чтобы получить ссылку на значок меню ящика. В моем случае позиция равна 2. Эта позиция должна быть равна количеству дочерних представлений в вашем пользовательском макете панели инструментов.
Если кто-то найдет лучшее решение, пожалуйста, дайте мне знать.
Если вы просто хотите получить Drawable
, представляющий значок навигации на панели инструментов, вы можете сделать это:
Drawable d = mToolbar.getNavigationIcon();
Вы можете получить ссылку на ImageButton, используемую для значка навигации панели инструментов, используя следующий метод:
public ImageButton getToolbarNavigationButton() {
int size = mToolbar.getChildCount();
for (int i = 0; i < size; i++) {
View child = mToolbar.getChildAt(i);
if (child instanceof ImageButton) {
ImageButton btn = (ImageButton) child;
if (btn.getDrawable() == mToolbar.getNavigationIcon()) {
return btn;
}
}
}
return null;
}
Импровизированный ответ @Nikola Despotoski
public static View getNavigationIconView(Toolbar toolbar) {
String previousContentDescription = (String) toolbar.getNavigationContentDescription();
// Check if contentDescription previously was set
boolean hadContentDescription = !TextUtils.isEmpty(previousContentDescription);
String contentDescription = hadContentDescription ?
previousContentDescription : "navigationIcon";
toolbar.setNavigationContentDescription(contentDescription);
ArrayList<View> potentialViews = new ArrayList<>();
// Find the view based on it's content description, set programmatically 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(previousContentDescription);
return navIcon;
}
((ViewGroup)yourtoolbar).get(0);
это может быть0
или1
, но я уверен, что это ноль, кстати, это то, что вы хотите? он вернетView
, аView
- это значок вашего ящика, возможно,imageButton
- person Elltz   schedule 28.04.2015View drawerIcon = toolbar.getChildAt(0);
Он не возвращает правильный вид (он возвращает вид, который представляет собой изображение в середине моей панели инструментов). @JaredBurrows Это не важно, но если вам интересно, я разработал учебный модуль, который принимает вид в качестве параметра и выделяет его, делая экран темным, оставляя круг вокруг целевого вида видимым. Я хочу, чтобы значок навигации на панели инструментов был выделен. - person Singed   schedule 30.04.2015