inflate方法的两种不同签名的区别

The difference between the two different signature of the methods of inflate

我在我的应用程序中为微调器定制了一个 ArrayAdapter。 这是其 getDropDownView() 方法的代码:

@Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        View vista = convertView;               
        if (vista==null) {
            LayoutInflater inflater =  (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            vista = inflater.inflate(R.layout.row_spinner,null);
        }

        TextView tv = (TextView) vista.findViewById( R.id.textview_entry );

        if( !Utils.isSDKAbove( Utils.HONEY_COMB ) )
        {
            tv.setTextColor( getContext().getResources().getColor( android.R.color.primary_text_light ) );
        }

        tv.setText( getItem( position ) );

        return vista;
    } 

当 tv.setText() 时,它为 TextView 抛出 NullPointerException。

但是,当我更改

vista = inflater.inflate(R.layout.row_spinner, null);

vista = inflater.inflate(R.layout.row_spinner, parent, false);

有效。

有人可以解释一下方法的两种不同签名之间的区别吗?

通过声明父根视图,您正在为该视图提供父 xml 布局。第三个布尔参数然后确定此子视图是否附加到父视图。从而判断子视图是否继承了父视图的触摸方法。

无论哪种方式,视图都需要根据 xml 布局进行透视,以便您所做的自定义和 xml 结构将在整个视图层次结构中实现。

使用膨胀 (layout, parent, false) 您正在使用父布局来膨胀视图(在本例中为微调器) 无需将其附加到父视图。 使用 null 您没有为视图提供任何布局参数,因此文本视图的 xml 的布局参数不存在。

来自the docs

root Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)

attachToRoot Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

Returns
The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.

使用 null 不是将视图与父视图分离的好方法,除非它是一个独立的功能,例如警报对话框。

视图需要一个根视图,有时传递 null 是可行的,但这只是因为程序试图为视图创建默认 xml 参数。

This article 更详细。

So why do you suppose we are given this ViewGroup if we are not supposed to attach to it? It turns out the parent view is a very important part of the inflation process because it is necessary in order to evaluate the LayoutParams declared in the root element of the XML being inflated. Passing nothing here is akin to telling the framework “I don’t know what parent this view will be attached to, sorry.”

The problem with this is android:layout_xxx attributes are always be evaluated in the context of the parent view. As a result, without any known parent, all LayoutParams you declared on the root element of your XML tree will just get thrown away, and then you’ll be left asking “why is the framework ignoring the layout customizations I defined? I’d better check SO and then file a bug.”