Android开发-LayoutInflater类

 

1.概述

1.1 定义

         加载布局的任务通常都是在Activity中调用setContentView()方法来完成的,其实setContentView()方法内部也是是由LayoutInflater来加载布局的

        LayoutInflater是一个抽象类继承自Object,位于android.view包下,作用类似于findViewById(),但是不同的是,LayoutInflater找的是xml布局文件并且实例化,而finViewById()是找到具体的widget控件

1.2 使用场景

          动态的载入一个xml布局,将xml布局文件实例化为它对应的View对象,从而获取其中的控件。比如在ScrollView、ListView和RecycleView中,动态的加入子item。

2.创建

2.1 获取LayoutInflater实例

       LayoutInflater这个类不能直接使用,即不能直接调用其成员,必须先获取其实例才能使用。获取实例的方法如下所示:

2.1.1 方式一

LayoutInflater inflater = getLayoutInflater();
//说明:getLayoutInflater()是Activity类中的方法,直接在Activity类中调用

2.1.2 方式二

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

2.1.3 方式三

LayoutInflater inflater = LayoutInflater.from(context);
//说明:context是当前上下文

        可以看出,方式三就是方式二的简单写法,只是Android做了一下封装

2.2 使用LayoutInflater的inflate()方法加载布局文件

         inflate()方法有如下几种重载的方法:

方法1:public View inflate(XmlPullParser parser, ViewGroup root)
方法2:public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)
方法3:public View inflate(int resource, ViewGroup root)
方法4:public View inflate(int resource, ViewGroup root, boolean attachToRoot)

//说明:方法1和方法2是通过XmlPullParser作为数据源创建View对象;方法3和方法4是通过resource目录下的布局文件
       作为数据来源创建View对象
//说明:参数resrource表示就是要加载的布局的id
       参数root表示给该布局的外部再嵌套一层父布局,如果不需要,则传入null

 

3.实例

3.1 代码和布局

         1)activity_main.xml中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

</LinearLayout>

         2)自定义一个包含按钮的布局:

<Button xmlns:android:"http://shcemas.android.com/apk/res/android"
    android:layout_width="wra_content"
    android:layout_height="wrap_content"
    android:text="Button">

</Button>

         3)MainActivity中:

public class MainActivity extends Activity{
    @Override
    public void onCreate(Bundled savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        LinearLayout mainLayout = findViewById(R.id.main_layout);
        LayoutInflater inflater = LayoutInflater.from(this);
        View buttonLayout = inflater.inflater(R.layout.button_layout,null);
        mainLayout.addView(buttonLayout);
    }
    
}

3.2 效果

       如下图所示:按钮被添加到了页面中:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luckyliuqs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值