我想突出顯示我的Toolbar
中的抽屜圖標(正在製作教程)。爲此,我需要它的位置。如何獲得抽屜導航圖標(漢堡包)視圖的參考?獲取工具欄的導航圖標視圖參考
11
A
回答
16
您可以使用視圖的內容描述,然後用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;
}
+7
有趣,但爲什麼我們必須這樣做。爲什麼沒有像'toolbar.getNavigationIconView()'那樣的東西 – Singed
6
在調試模式下查看工具欄的子視圖後,我看到可以在那裏找到作爲ImageButton的抽屜圖標。 (感謝Elltz)
我用一個工具欄與2名兒童(的LinearLayout和ImageView的)自定義XML佈局,所以我的工具欄有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.這個位置應該等於您的自定義工具欄佈局中子視圖的數量。
如果有人找到更好的解決方案,請讓我知道。
4
如果你只是想獲得Drawable
代表的工具欄導航圖標,你可以這樣做:
Drawable d = mToolbar.getNavigationIcon();
您可以獲得對ImageButton的引用,用於由具有方法,因爲這olbar的導航圖標:
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;
}
相關問題
- 1. 色調導航圖標在工具欄
- 2. 從導航欄視圖控制器導航到標籤欄視圖控制器
- 3. 導航欄的標題視圖重疊
- 4. Android的導航工具欄圖標和標識不能對齊
- 5. 工具欄和導航繪圖器
- 6. 工具欄隱藏導航圖像
- 7. 獲取導入工具欄圖標的錯誤
- 8. 導航欄視圖爲模態視圖?
- 9. 導航欄按下視圖
- 10. 在工具欄中調整導航圖標的大小
- 11. 使用工具欄在視圖之間導航
- 12. 如何在iOS視圖中保留導航工具欄
- 13. 如何使用工具欄(humburger圖標)作爲後臺導航
- 14. 如何獲取子視圖中導航欄的高度?
- 15. 獲取導航抽屜滑動工具欄/操作欄下方
- 16. Android:獲取視圖參考菜單項
- 17. UserControl.Resources /獲取參考視圖模型
- 18. 獲取視圖控制器參考
- 19. 從Widget參考中獲取視圖
- 20. 從TouchesMoved獲取子視圖參考
- 21. 如何在下一個視圖的導航欄上獲取標籤的文字?
- 22. iOS:意外覆蓋導航欄的表格視圖標題欄
- 23. 當我使用popViewControllerAnimated獲取空視圖和空白導航欄
- 24. 中心工具欄標題自定義工具欄中的圖標和導航抽屜切換按鈕
- 25. 更改導航欄和工具欄中的導航控制器作爲視圖的色調
- 26. Matplotlib導航工具欄
- 27. 離子導航欄的視圖
- 28. 導航欄標題視圖重疊左欄按鈕項目
- 29. 如何縮小導航圖標和工具欄標題之間的差距?
- 30. 獲取片段的Android工具欄子視圖
'((ViewGroup中)yourtoolbar)獲得(0);'可能是'0'或'1'但是我相信它的零,順便說一句這是什麼你要?它會返回一個'View'並且'View'是你的抽屜圖標也許是一個'imageButton' – Elltz
你是什麼意思「突出顯示」抽屜圖標? –
您確定需要突出顯示的視圖嗎?例如,您可以獲取用於圖標的繪圖。 –