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

青春壹個敷衍的年華 提交于 2019-12-02 20:06:45

I would simply do it like this:

menuItem.setActionView(R.layout.action_view_layout);

Let Android inflate the view for you.

If you need to do some extra changes on this ImageView call

ImageView imageView = (ImageView) menuItem.getActionView();

Update

In order to cater to your curiosity. That is what folks from Google do under the hood:

public MenuItem setActionView(int resId) {
    final Context context = mMenu.getContext();
    final LayoutInflater inflater = LayoutInflater.from(context);
    setActionView(inflater.inflate(resId, new LinearLayout(context), false));
    return this;
}

You have look on this. it nicely explains the Layout Inflator as well.

There are two usable versions of the inflate() method for a standard application:

inflate(int resource, ViewGroup root)
inflate(int resource, ViewGroup root, boolean attachToRoot)

The first parameter points to the layout resource you want to inflate. The second parameter is the root view of the hierarchy you are inflating the resource to attach to. When the third parameter is present, it governs whether or not the inflated view is attached to the supplied root after inflation.

It is these last two parameters that can cause a bit of confusion. With the two parameter version of this method, LayoutInflater will automatically attempt to attach the inflated view to the supplied root. However, the framework has a check in place that if you pass null for the root it bypasses this attempt to avoid an application crash.

Many developers take this behavior to mean that the proper way to disable attachment on inflation is by passing null as root; in many cases not even realizing that the three parameter version of inflate() exists.

More on Layout Inflation

user2399268

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!