按钮用于添加项目的操作

时间:2014-02-12 16:17:21

标签: android-layout

如何使用同一布局上的按钮向活动布局添加更多项目。项目包括TextViews,EditViews等项目,这些项目需要添加到按钮所在的同一布局中。请帮帮我。考虑一下Android开发中的菜鸟。

1 个答案:

答案 0 :(得分:0)

由于您尝试通过按钮添加项目,因此必须以编程方式添加组件。

以下是如何通过单击按钮以编程方式添加按钮的示例:

final Activity act = this;
//the layout on which you are working
//if using LinearLayout cast it correctly
final RelativeLayout layout = (RelativeLayout) findViewById(R.id.layout_general);

Button btnAdd = (Button)findViewById(R.id.btn_add);

btnAdd.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {


        //set the properties for button
        Button btnTag = new Button(act);
        //if using LinearLayout change to LinearLayout.LayoutParams
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT,      
                LayoutParams.WRAP_CONTENT
        );
        //Set place in layout, make sure you change the values everytime you insert
        //another item otherwise the items will be placed on top of each other
        params.setMargins(200, 40, 100, 50);
        btnTag.setLayoutParams(params);
        btnTag.setText("Button");

        //add button to the layout
        layout.addView(btnTag);

    }
});

将此代码段添加到onCreate()并进行正确的名称更改,您就可以了。

希望它有所帮助。