如何以编程方式创建按钮?

时间:2011-11-10 12:54:12

标签: android android-button

我只想在我想要时动态地将按钮添加到我的布局中。 按钮应该像这个XML Button:

 <Button android:text="Text" 
 android:gravity="bottom" 
 android:textSize="10dp" 
 android:textColor="#FFFFFF" 
 android:layout_width="wrap_content"
 android:background="@drawable/attack1"
 android:layout_height="wrap_content" 
 android:id="@+id/workingButton">
 </Button>

public class GravityIssueActivity extends Activity
{
    LinearLayout layout;
    Button newButton;
    Button buttonByXml;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //the button in the xml file
        buttonByXml = (Button)findViewById(R.id.workingButton);
        layout = (LinearLayout)findViewById(R.id.layoutToInsert);
        //my new programatically "born" button
        newButton = new Button(this);
        //Setting the properties as i want
        newButton.setText("Text");
        newButton.setTextSize(10);
        newButton.setTextColor(Color.WHITE);
        newButton.setBackgroundResource(R.drawable.attack1);
        // Gravity = Bottom !!!!!!!!!!
        newButton.setGravity(Gravity.BOTTOM);
        // getting the XML buttons params just for case...
        newButton.setLayoutParams(new LayoutParams(buttonByXml.getLayoutParams()));
        //Adding my new Button to the layout
        layout.addView(newButton);
    }
}

以下是结果图片:

enter image description here

当我复制所有属性时,如何才能成为不同的结果?

5 个答案:

答案 0 :(得分:1)

如果你想创建动态视图(如Button,textview等),那么只需使用此代码并在你的应用程序中运行它。

MyActivity.java:你的java文件

 LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
 Button btn = new Button(this)
 btn.setText("My Dynamic Button);
 btn.setMinLines(1);
 btn.setMaxLines(3);
 ll.addView(et);

在XML文件中:

 <LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignBottom="@+id/TextView01"
android:layout_below="@+id/relativeLayout1"
android:orientation="vertical" >

答案 1 :(得分:0)

您绝对可以在代码中创建按钮,但除非您有充分的理由动态创建控件,否则它不被视为最佳实践。看看这篇文章Add an array of buttons to a GridView in an Android application

答案 2 :(得分:0)

尝试使用

 Button b = new Button();

这为您提供了一个可以添加到当前父活动或fragmnet视图的View实例。有关可能设置的完整参考,请查看http://developer.android.com/reference/android/widget/Button.html

您可以使用对象层次结构中父视图提供的所有设置方法。

答案 3 :(得分:0)

如果您需要将文字对齐到按钮的底部,您只需要:

Button button = ...
//apply required paramteres
button.setGravity(Gravity.BOTTOM);

答案 4 :(得分:0)

使用下面的代码。您还可以添加其他参数

    Button submit=new Button(this);
    LinearLayout.LayoutParams params= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    params.setMargins(25, 0, 25, 0);
    submit.setLayoutParams(params);
    submit.setText("Attack");
    submit.setTextSize(10);
    submit.setTextColor(getResources().getColor(R.color.white));
    submit.setBackgroundResource(R.drawable.attack);
相关问题