標籤:android style blog http io color os ar 使用
LayoutInflater類在應用程式中比較實用,可以叫布局填充器,也可以成為打氣筒,意思就是將布局檔案填充到自己想要的位置,LayoutInflater是用來找res/layout/下的xml布局檔案,並且執行個體化這個XML檔案成為一個View,有點類似於類似於findViewById(),但是findViewById()是找xml布局檔案下的具體widget控制項(Button、TextView)。對於一個沒有被載入或者想要動態載入的介面,都需要使用LayoutInflater.inflate()來載入;對於一個已經載入的介面,使用Activiyt.findViewById()方法來獲得其中的介面元素。
LayoutInflater執行個體方式
首先簡單看下三種簡單的執行個體方式:
LayoutInflater layoutInflater = getLayoutInflater();LayoutInflater layoutInflater2 = LayoutInflater.from(this);LayoutInflater layoutInflater3 = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
第一種getLayoutInflater方式:
public LayoutInflater getLayoutInflater() { return getWindow().getLayoutInflater(); }
第二種實現方式:
public static LayoutInflater from(Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { throw new AssertionError("LayoutInflater not found."); } return LayoutInflater; }
後兩種調用的都是getSystemService,第一種也是~
LayoutInflater實現Demo
LayOutInflater填充布局的時候有四種方法,Demo使用第一種:
resource:需要載入布局檔案的id,需要將這個布局檔案中載入到Activity中來操作。
root:inflate()會返回一個View對象如果root不為null,就將這個root作為根對象返回,作為這個xml檔案的根視圖,如果是null,那麼這個xml檔案本身就是一個根視圖:
public View inflate (int resource, ViewGroup root) public View inflate (XmlPullParser parser, ViewGroup root) public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot) public View inflate (int resource, ViewGroup root, boolean attachToRoot)
看下實現的結果:
在主表單中定義一個按鈕,這個代碼就不貼了~直接寫點擊事件的處理吧:
定義一個Item檔案:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/test" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/inflate_txt" android:layout_width="match_parent" android:layout_height="match_parent" android:text="測試"/></LinearLayout>
點擊事件的處理:
LayoutInflater layoutInflater = getLayoutInflater();View view = layoutInflater.inflate(R.layout.item, null);TextView text = (TextView) view.findViewById(R.id.inflate_txt);text.setText("http://www.cnblogs.com/xiaofeixiang");text.setTextSize(18);text.setTextColor(Color.RED);AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);builder.setView(view);AlertDialog alertDialog = builder.create();alertDialog.show();
Android資料填充器LayoutInflater