我如何编程创建一个按钮? [英] How do I create a button programatically?

查看:196
本文介绍了我如何编程创建一个按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想要动态按钮添加到我的布局时,我想。
按钮应该是这样的XML按钮:

I just want to dynamicly add buttons to my Layout when i want to. The buttons should be like this 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);
    }
}

这是结果的图像:

这怎么可能成为不同的结果,当我复制所有的属性?

How is it possible to became different result when I copy all the attributes?

推荐答案

如果你想创建动态视图(如按钮,TextView的等),那么就使用这个code和在应用程序中运行它。

If you want to create dynamic view (like Button,textview etc) then just use this code and run it in your application.

MyActivity.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" >

这篇关于我如何编程创建一个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆