首先瞭解一下LayouInflater類:將一個layout xml檔案執行個體化為相應的View 對象。他永遠不會直接使用,而是使用 getLayoutInflater() 或者 getSystemService(String) 來獲得標準的LayoutInflater執行個體,這個執行個體已經將context串連起來,為正在啟動並執行裝置配置正確。比如:[java] view plaincopyLayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); public View inflate (int resource, ViewGroup root)Since: API Level 1Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.Parametersresource ID for an XML layout resource to load (e.g., R.layout.main_page) root Optional view to be the parent of the generated hierarchy.ReturnsThe root View of the inflated hierarchy. If root was supplied, this is the root View; otherwise it is the root of the inflated XML file.假如有一個這樣的xml檔案(guess_button.xml) 放入到一個buttonTableLayout:[html] view plaincopy<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/newGuessButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> (guess_button.xml)[html] view plaincopy<TableLayout android:id="@+id/buttonTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:stretchColumns="0,1,2" > <TableRow android:id="@+id/tableRow0" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> </TableRow> <TableRow android:id="@+id/tableRow1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> </TableRow> <TableRow android:id="@+id/tableRow2" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> </TableRow> </TableLayout> (main.xml中定義的需要被擴充的buttonTableLayout,假設其在程式中的引用也叫buttonTableLayout, 即buttonTableLayout =(TableLayout) findViewById(R.id.buttonLayout);)現在我們將其第一行進行擴充:[java] view plaincopyLayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); Button newGuessButton =(Button)inflater.inflater(R.layout.guess_button,null); //獲得按鈕 newGuessButton.setText("abc"); //設定按鈕文本 newGuessButton.setOnClickListener(guessButtonListener); //設定Listener (TableRow) buttonTableLayout.getChildAt(1); //將newGuessButton加到table第一行 OK 整個流程就完成了