首先了解一下LayouInflater类: 将一个layout xml文件实例化为相应的View 对象。他永远不会直接使用,而是使用 getLayoutInflater() 或者 getSystemService(String) 来获得标准的LayoutInflater实例,这个实例已经将context连接起来,为正在运行的设备配置正确。 比如: [java] view plaincopy LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); public View inflate (int resource, ViewGroup root) Since: API Level 1 Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error. Parameters resource 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. Returns The 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 plaincopy LayoutInflater 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 整个流程就完成了
安卓动态增加按钮
最新推荐文章于 2022-11-18 07:55:19 发布