11

我想突出顯示我的Toolbar中的抽屜圖標(正在製作教程)。爲此,我需要它的位置。如何獲得抽屜導航圖標(漢堡包)視圖的參考?獲取工具欄的導航圖標視圖參考

+1

'((ViewGroup中)yourtoolbar)獲得(0);'可能是'0'或'1'但是我相信它的零,順便說一句這是什麼你要?它會返回一個'View'並且'View'是你的抽屜圖標也許是一個'imageButton' – Elltz

+0

你是什麼意思「突出顯示」抽屜圖標? –

+0

您確定需要突出顯示的視圖嗎?例如,您可以獲取用於圖標的繪圖。 –

回答

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

More

+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; 
}