2014-02-12 69 views
-1

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

回答

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(),并作出适当的名称的变化,你是好去。

希望它有帮助。