inflate方法与getViewByID和setContentView的区别
2017-07-28 22:05
344 查看
在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。
具体作用:
1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。
LayoutInflater作用是将layout的xml布局文件实例化为View类对象。获取LayoutInflater的方法有如下三种:
注意:
·inflate方法与 findViewById 方法不同;
·inflater 是用来找 res/layout下的 xml 布局文件,并且实例化;
·findViewById() 是找具体 xml 布局文件中的具体 widget 控件(如:Button、TextView 等)。
对于inflate与setContentView()区别:
setContentView()一旦调用, layout就会立刻显示UI;而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来。一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这就需要LayoutInflater动态加载。
关于inflate方法:
public View inflate(int Resourece,ViewGroup root)
作用:填充一个新的视图层次结构从指定的XML资源文件中
reSource:View的layout的ID
root: 生成的层次结构的根视图
return 填充的层次结构的根视图。如果参数root提供了,那么root就是根视图;否则填充的XML文件的根就是根视图。
下面举例说明。
上述注释掉的代码和没有注释掉的代码两种情况是相同的。
具体作用:
1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。
LayoutInflater作用是将layout的xml布局文件实例化为View类对象。获取LayoutInflater的方法有如下三种:
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = LayoutInflater.from(context); (该方法实质就是第一种方法,可参考源代码) View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,实际上是View子类下window的一个函数) View layout = inflater.inflate(R.layout.main, null);
注意:
·inflate方法与 findViewById 方法不同;
·inflater 是用来找 res/layout下的 xml 布局文件,并且实例化;
·findViewById() 是找具体 xml 布局文件中的具体 widget 控件(如:Button、TextView 等)。
对于inflate与setContentView()区别:
setContentView()一旦调用, layout就会立刻显示UI;而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来。一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这就需要LayoutInflater动态加载。
关于inflate方法:
public View inflate(int Resourece,ViewGroup root)
作用:填充一个新的视图层次结构从指定的XML资源文件中
reSource:View的layout的ID
root: 生成的层次结构的根视图
return 填充的层次结构的根视图。如果参数root提供了,那么root就是根视图;否则填充的XML文件的根就是根视图。
下面举例说明。
上述注释掉的代码和没有注释掉的代码两种情况是相同的。
相关文章推荐
- 【转】Android之Inflate()方法用途+setContentView和inflate区别
- Android之Inflate()方法用途+setContentView和inflate区别
- setContentView和inflate区别
- inflate, findViewById与setContentView的区别与联系
- AppCompatActivity和Activity的setContentView方法的区别
- Android之Inflate()方法用途+setContentView和inflate区别
- inflate, findViewById与setContentView的区别与联系
- setContentView()和inflate()的区别
- Android中setContentView、addContentView、inflate、LayoutInflater和findViewById()区别
- setContentView和inflate区别
- setContentView和inflate区别
- Android之Inflate()方法用途+setContentView和inflate区别
- setContentView和inflate区别
- setContentView和inflate区别
- inflate, findViewById与setContentView的区别与联系
- setContentView和inflate区别
- Android setContentView和inflate区别
- setContentView和inflate区别
- setContentView和inflate区别
- setContentView和inflate区别