在Android中的运行时向LinearLayout添加新按钮

时间:2014-09-06 21:20:09

标签: java android

我想在运行时添加新的Button以及所有属性,如下所示。

<LinearLayout
                android:id="@+id/linearLayout1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:orientation="horizontal" >

                <Button
                    android:id="@+id/btnMM"
                    android:layout_width="0dip"
                    android:layout_height="fill_parent"
                    android:layout_weight="1"
                    android:background="@drawable/android_btn_md"
                    android:gravity="center"
                    android:onClick="btnMMClick"
                    android:text="M-"
                    android:textColor="#000000"
                    android:textSize="25sp"
                    android:textStyle="bold" /> 

 ...... more buttons at design time are here .....

谢谢, 阿肖克

1 个答案:

答案 0 :(得分:1)

考虑到你是新手:

Button myButton = new Button(context);
LinearLayout.LayoutParams lparms = new LinearLayout.LayoutParams(0,LayoutParams.FILL_PARENT);
lparms.weight = 1;
lparms.gravity = Gravity.CENTER;
myButton.setLayoutParams(lparms);
myButton.setBackground(getResources().getDrawable(R.drawable.android_btn_md));
myButton.setOnClickListener(btnMMClick);
myButton.setText("M-");
myButton.setTextColor(Color.parseColor("#000000"));
myButton.setTextSize(25);
myButton.setTypeface(null, Typeface.BOLD);