一,概述。
使用LayoutInflater,可以在res/layout下找到需要的XML文件,并可以得到其实例。
findViewById是用来找xml布局文件下的具体widget控件(如Button、TextView等)。
作用:
1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。
获得 LayoutInflater 实例的三种方式
1. LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
例:View toastRoot = getLayoutInflater().inflate(R.layout.toast, null);
2. LayoutInflater localinflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3. LayoutInflater inflater = LayoutInflater.from(context);
例:View convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_contact, null);
二,inflater。
通俗的说,inflate就相当于将一个xml中定义的布局找出来.因为在一个Activity里如果直接用findViewById()的话,对应的是setConentView()的那个layout里的组件.
因此如果你的Activity里如果用到别的layout,比如对话框上的layout,你还要设置对话框上的layout里的组件(像图片ImageView,文字TextView)上的内容,你就必须用inflate()先将对话框上的layout找出来,然后再用这个layout对象去找到它上面的组件,如:
View view=View.inflate(this,R.layout.dialog_layout,null);
TextView dialogTV=(TextView)view.findViewById(R.id.dialog_tv);
dialogTV.setText("abcd");
如果组件R.id.dialog_tv是对话框上的组件,而你直接用this.findViewById(R.id.dialog_tv)肯定会报错.
三,例子。
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<RelativeLayout
android:id="@+id/viewgroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</RelativeLayout>
</LinearLayout>
inflatertest.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="inflatedemo" />
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private RelativeLayout mViewGroup;
private LayoutInflater mInflater;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewGroup = (RelativeLayout) findViewById(R.id.viewgroup);
mInflater = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
// mInflater.inflate(R.layout.inflatertest, mViewGroup);
// mInflater.inflate(R.layout.inflatertest, mViewGroup, true);
mInflater.inflate(R.layout.inflatertest, mViewGroup, false);
}
}
代码的意思是,MainActivity加载了activity_main.xml的内容,这时候,当xml中的RelativeLayout想要加载新的xml时,需要使用LayoutInflater从res/layout中找到
inflatertest.xml并用inflater将其部署进RelativeLayout中。
以上有三种方式,
第二种方式第二个参数指的是将第一个参数获得的xml放入自己中。