歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中LayoutInflater的使用

Android中LayoutInflater的使用

日期:2017/3/1 9:57:11   编辑:Linux編程

首先對LayoutInflater下一個定義吧,Layoutinflater的作用就是將一個xml布局文件實例化為View對象。

獲取Layoutinflater對象的方法有三種,招不在多,管用就行,跟蹤源碼後發現三種方法的本質都是調用了context.getSystemService(),所以建議以後寫的時候就用context.getSystemService()。具體寫法如下:

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

接下來重點介紹inflate()方法的使用:

1、返回值:

View對象,有了View對象我們就能做諸如setContentView()或者在自定義Adapter裡面的getView()方法中獲取item的布局。

2、參數:

public View inflate (int resource, ViewGroup root)

第一個參數是一個xml文件的R索引,比如R.layout.activity_main。第二個參數如果不為null就是將得到的View對象再放入一個Viewgroup容器中,我這麼說可能有的讀者還不是很清楚,文章的最後會有一個例子來說明問題。

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

這裡的第三個參數的意思是如果第二個參數不為null,那麼為true則放入第二個參數引用的Viewgroup中,為false則不放入第二個參數的Viewgroup中。

下面用一個實例來說明問題。

布局文件有兩個:

activity_main.xml

<LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
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>

當Activity中如是寫:

@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);
}

或者

@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, true);
}

結果是這樣子的:

Copyright © Linux教程網 All Rights Reserved