setContentView(),inflate()方法

通常在创建一个Activity的时候,我们会在onCreate()方法中调用setContentView()方法,并且为setContentView()方法传递一个int类型的

值(即某个布局文件的id),用来表示当前Activity创建的时候要显示的view。


而在非Acticity中,如何将一个布局文件转换为一个View对象并显示

呢?可以理解为在程序中动态加载,用下面两句代码:

1.LayoutInflater inflater = LayoutInflater.from(this);

//LayoutInflater类的静态方法:public static LayoutInflate from(Context context)

//通过系统服务获得:LayoutInflater inflater = (LayoutInflater context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

2.View view = inflater.inflate(xmlId,null);


View类的inflate()方法:(内部还是用LayoutInflater实现的

static View inflate(Context context,int resource,ViewGroup root)

第一个参数:Activity或Application的上下文

第二个参数:指定的xml布局

第三个参数:指定父控件

View view = View.inflate(this,xmlId,null);


inflate(xmlId,null):xml的父控件的宽高是没有效果的,返回xml

inflate(xmlId,root,false):xml的父控件的宽高是没有效果的,返回xml

inflate(xmlId,root,true):xml的父控件的宽高可以正常显示,返回root

(这里的父控件就是ViewGroup)


那为什么用setContentView()方法就可以显示父控件呢?这是因为在调用

setContentView()方法的时候系统会默认为xml文件添加一个FrameLayout的父控件

猜你喜欢

转载自blog.csdn.net/Dream_Ryoma/article/details/52927790