Android开发中setContentView和inflate的区别分析


本文实例讲述了Android开发中setContentView和inflate的区别。分享给大家供大家参考,具体如下:

一般用LayoutInflater做一件事:inflate

inflate这个方法总共有四种形式(见下面),目的都是把xml表述的layout转化为View对象。

其中有一个比较常用,View inflate(int resource, ViewGroup root),另三个,其实目的和这个差不多。

int resource,也就是resource/layout文件在R文件中对应的ID,这个必须指定。

而ViewGroup root则可以是null,null时就只创建一个resource对应的View,不是null时,会将创建的view自动加为root的child。

setContentView和inflate区别:

setContentView()一旦调用, layout就会立刻显示UI;而inflate只会把Layout形成一个以view类实现成的对象,有需要时再用setContentView(view)显示出来

一般在activity中通过setContentView()将界面显示出来,但是如果在非activity中如何对控件布局设置操作了,这需LayoutInflater动态加载

<TextView
android:id="@+id/tview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="ATAAW.COM"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="按钮"
/>

在程序中动态加载以上布局。

LayoutInflater flater = LayoutInflater.from(this);
View view = flater.inflate(R.layout.example, null);

获取布局中的控件。

button = (Button) view.findViewById(R.id.button);
textView = (TextView)view.findViewById(R.id.tview);

接下来结合源码说说inflate方法的四种形式:

inflate方法总共有四种形式,把xml表达的layout转化为view. This class is used to instantiate layout xml files into its corresponding view object. It is never be used directly——use getLayoutInflater() or getSystemService(String)getLayoutInflate() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up that is already hook up to the current context and correct configured for the device you are running on.

1. Context.public abstract object getSystemService(String name)

2. 两种获得LayoutInflater的方法

a. 通过SystemService获得

Android编程之activity操作技巧总结》、《Android视图View技巧总结》、《Android操作SQLite数据库技巧总结》、《Android操作json格式数据技巧总结》、《Android数据库操作技巧总结》、《Android文件操作技巧汇总》、《Android编程开发之SD卡操作方法汇总》、《Android开发入门与进阶教程》、《Android资源操作技巧汇总》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。


« 
» 

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3