What should I pass for root when inflating a layout to use for a MenuItem's ActionView?

后端 未结 3 1564
暖寄归人
暖寄归人 2021-02-01 14:23

I have an ImageView that I attach to a MenuItem as its ActionView (the item appears in the ActionBar). The layout for this vi

3条回答
  •  野性不改
    2021-02-01 14:42

    You generally want to pass whatever (ViewGroup sub-class) you're going to be adding actionView to in to inflate. in order to get actionView back from the inflate call and not the parent you'll want to add a 3rd parameter, false, so that it won't add the inflated view to the parent.

    ImageView actionView = 
        (ImageView)layoutInflater.inflate(R.layout.action_view_layout, parent, false);
    // .. do whatever you like with actionView and then add it to it's parent
    menuItem.addActionView(actionView)
    

    There's a pretty good tutorial here that goes about things a little differently. It's specifying action_view_layout as part of menu.xml with something like:

    android:actionLayout="@layout/action_view_layout"
    

    That may also work for you provided you're always using the same layout. if you go that route you'd be able to get the ActionView by doing

    ImageView actionView = menu.findItem(R.id.whatever).getActionView();
    

提交回复
热议问题