2012年4月15日星期日

安卓动态增加按钮

安卓动态增加按钮



首先了解一下LayouInflater类:将一个layout = (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 if there is an error.Parametersresource     ID for an this is the root View; otherwise it is the root of the inflated <?      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.<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.=(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 整个流程就完成了


TAG:phone 开发