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

Android 如何以编程方式创建按钮?,android,android-button,Android,Android Button,我只想在需要的时候动态地将按钮添加到布局中。 按钮应类似于此XML按钮: <Button android:text="Text" android:gravity="bottom" android:textSize="10dp" android:textColor="#FFFFFF" android:layout_width="wrap_content" android:background="@drawable/attack1" android:layout_heig

我只想在需要的时候动态地将按钮添加到布局中。 按钮应类似于此XML按钮:

 <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>
下面是结果的图像:


当我复制所有属性时,如何可能得到不同的结果?

您完全可以在代码中创建按钮,但这不是最佳做法,除非您有充分的理由动态创建控件。查看此帖子。

尝试使用

 Button b = new Button();
这将为您提供一个视图实例,可以将其添加到当前父活动或fragmnet视图中。有关可能设置的完整参考,请参阅


可以使用对象层次结构中父视图提供的所有集合方法

如果需要将文本与按钮底部对齐,则只需:

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

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

    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);

如果您想创建动态视图(如按钮、文本视图等),那么只需使用此代码并在应用程序中运行它

我的活动。java://your 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" >


老实说,我只是在重力方面有问题。我无法使文本位于底部。LinearLayout.LayoutParams params=新的LinearLayout.LayoutParams(LayoutParams.WRAP\u内容,LayoutParams.FILL\u父项);params.gravity=80不起作用,你需要gravity来对齐按钮内部的文本,或者对齐按钮的父按钮内部的文本?我只希望按钮的文本与按钮的底部对齐:)可能重复我刚刚尝试过它-但显然是默认背景-两个按钮看起来几乎相同。HTC Desire S,Android 2.3.5(2.1 emulator上的结果相同)我的代码有点问题,因为这个snipet在按钮底部和文本之间留下了一个空白。这就是我发布这个问题的原因。。。我就是不明白。你能提供你得到的结果吗?在没有看到它的情况下,我只能假设您设置了
setlinespace()
的值大于必需值,或者在用于设置按钮文本的字符串末尾有
\n
。我没有使用setlinespace(),如果我使用上面的XML代码,我会得到一个底部有文本的漂亮图像按钮。如果我尝试创建一个类似.setGravity(Gravity.BOTTOM)的代码,则文本和按钮底部之间有一个空白。@AdamVarhegyi是
layoutToInsert
LinearLayout,包含第一个(工作)按钮?是。它包含两个按钮。融合错误,我已经坚持了一天。设置的边距在不同分辨率的设备上会产生相同的结果吗?
 <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" >