美文网首页
Android——LayoutInflater

Android——LayoutInflater

作者: 鱼嘿蛮仁 | 来源:发表于2024-09-23 17:41 被阅读0次

一、LayoutInflater 的作用:
LayoutInflater是Android中用于将XML布局文件转换为View的重要工具。它在Activity、Fragment和Adapter中有广泛应用,如创建界面视图。此外,通过Context获取LayoutInflater服务也是其常见操作。总之,LayoutInflater的主要职责是布局加载。

二、LayoutInflater和findViewById()的不同点:
1、LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。
2、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。

三、LayoutInflater的实例化方法:

LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()
LayoutInflater inflater = LayoutInflater.from(context);
LayoutInflater inflater =  (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

四、LayoutInflater.inflater方法:
1、inflate(int resource, ViewGroup root):这是最基本的方法,它接受一个布局资源ID和一个可选的父容器作为参数。如果attachToRoot默认为true,则此方法等同于调用inflate(int resource, ViewGroup root, boolean attachToRoot)方法时传入true作为第三个参数。

2、inflate(int resource, ViewGroup root, boolean attachToRoot):这是完全可配置的方法,允许开发者明确指定是否立即将新创建的视图附加到父容器。

参数:
resource:要加载的XML布局资源的ID。
root:可选的ViewGroup参数,作为新创建View的父容器。如果提供了父容器,inflate过程会考虑父容器的LayoutParams,并可能根据需要调整新创建视图的属性。
attachToRoot:是否应将新创建的View立即附加到提供的父容器中。如果为true,则新生成的视图层次结构会立即添加到父容器内;反之则不会立即附加,但可以手动添加。

五、应用场景:
1、在Activity中加载布局:

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.activity_main, null);

2、在Adapter中为ListView或RecyclerView加载布局:

public class MyAdapter extends ArrayAdapter<String> {
    public MyAdapter(Context context, int resource, List<String> objects) {
        super(context, resource, objects);
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
        }
        // 填充数据到布局
        return convertView;
    }
}

3、在自定义View中使用LayoutInflater:

public class CustomView extends View {
    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.your_layout, this, true);
    }
}

相关文章

网友评论

      本文标题:Android——LayoutInflater

      本文链接:https://www.haomeiwen.com/subject/wpdfrjtx.html