Android程序中动态添加Button

来源:互联网 发布:qq微信抢红包软件 编辑:程序博客网 时间:2024/05/25 19:59

        在代码中动态添加Button的难点是设置Btn的margin,其它的都好说,具体代码如下:

1、xml文件:

<?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">    <LinearLayout         android:id="@+id/btnListLayout"        android:orientation="vertical"        android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:background="@android:color/transparent"        ></LinearLayout></LinearLayout>

2、code:

public class AddBtnByCodeActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView( R.layout.add_btn_by_code_layout );findAllView( );generateBtnList( getBtnContentList( ) );}private void findAllView( ){mBtnListLayout = ( LinearLayout )findViewById( R.id.btnListLayout );}private ArrayList<String> getBtnContentList( ){ArrayList<String> btnContentList = new ArrayList<String>( );for( int index = 0; index < 10; index++ ){btnContentList.add( "动态Btn" + index );}return btnContentList;}private void generateBtnList( ArrayList<String> btnContentList ){if( null == btnContentList ){return;}mBtnListLayout.removeAllViews( );int index = 0;for( String btnContent : btnContentList ){Button codeBtn = new Button( this );setBtnAttribute( codeBtn, btnContent, index, Color.TRANSPARENT, Color.BLACK, 24 );mBtnListLayout.addView( codeBtn );index++;}}private void setBtnAttribute( Button codeBtn, String btnContent, int id, int backGroundColor, int textColor, int textSize ){if( null == codeBtn ){return;}codeBtn.setBackgroundColor( ( backGroundColor >= 0 )?backGroundColor:Color.TRANSPARENT );codeBtn.setTextColor( ( textColor >= 0 )?textColor:Color.BLACK );codeBtn.setTextSize( ( textSize > 16 )?textSize:24 );codeBtn.setId( id );codeBtn.setText( btnContent );codeBtn.setGravity( Gravity.LEFT );codeBtn.setOnClickListener( new OnClickListener( ) {@Overridepublic void onClick(View v) {// btn click process}});RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT );rlp.addRule( RelativeLayout.ALIGN_PARENT_LEFT );codeBtn.setLayoutParams( rlp );}private LinearLayout mBtnListLayout = null;}


原创粉丝点击