How to cast MenuItem to LinearLayout

2019-03-01 11:56发布

问题:

I have NavigationView with menus. I am able to get MenuItem from navigationView by using

MenuItem menuItem = navigationView.getMenu().getItem(0);
LinearLayout linearLayout = (LinearLayout) menuItem; 

I want to cast menuItem to LinearLayout or View.

I have set android:actionViewClass to menu in menu.xml :

 <item
    android:id="@+id/nav_backup"
    android:icon="@drawable/ic_sd_card_black_24dp"
    android:actionViewClass="android.widget.LinearLayout"
    android:title="@string/backup_configuration" />

While casting I am facing NullPointerException. How can I cast this?

回答1:

Try this first set custom layout to your MenuItem than cast it to LinearLayout like below code

MenuItem item = menu.findItem(R.id.action_cart);
MenuItemCompat.setActionView(item, R.layout.menu_layout);
LinearLayout linearLayout = (LinearLayout) MenuItemCompat.getActionView(item);

EDIT

setActionView() and getActionView() method was deprecated in API level 26.1.0.

Direct use MenuItem.setActionView() and MenuItem.getActionView()

SAMPLE CODE

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item = menu.findItem(R.id.action_menu);
        item.setActionView( R.layout.activity_main);
        LinearLayout linearLayout = (LinearLayout) item.getActionView();
        return super.onCreateOptionsMenu(menu);
    }