快速添加多个按钮 [英] Adding multiple buttons on the fly

查看:136
本文介绍了快速添加多个按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过单击按钮时的代码动态添加多个按钮,我搜索了很多以前的帖子,这些帖子显示要添加单个按钮,但是我需要多个按钮.

I want to add multiple buttons dynamically through the code on button click, I searched many previous posts which shows to add single button, but I need multiple ones.

附带的是示例代码.

   public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b1 = (Button)findViewById(R.id.button1);
        b1.setOnClickListener(new View.OnClickListener() {      
            @Override
            public void onClick(View v) {               
                AddAll();                   
            }
        });
    }
    public void AddAll() {
        final RelativeLayout rl = (RelativeLayout)findViewById(R.id.rel);
        final Button btn = new Button(this);
        for(int i=0;i<4;i++)
        {
            rl.addView(btn); 
            btn.setText("hello");
            btn.setWidth(320);
            btn.setHeight(40);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

请就此提供帮助.但是,添加单个按钮的效果很好,但是我需要在一个按钮的另一个下方添加许多按钮.

Please help regarding the same. However adding single button is working fine, but I need to add many buttons one below the other.

推荐答案

public void AddAll() {
final RelativeLayout rl = (RelativeLayout)findViewById(R.id.rel);

for(int i=0;i<4;i++)
{
    final Button btn = new Button(this);
    rl.addView(btn); 
    btn.setText("hello");

    btn.setWidth(320);
    btn.setHeight(40);
}
//////////////////////////////////////////////////////////
}

更多细节:-

How do I programmatically add buttons into layout one by one in several lines?

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ScrollView scrollView= new ScrollView(this);
    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.VERTICAL);                
    for (int i=0; i<10; i++){
        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setTag(i);                            
        TextView tv=new TextView(this);
        tv.setText("Row " + i);            
        ll.addView(tv);
        Button b = new Button(this);
        b.setTag(i);
        b.setText("Button " + i);            
        ll.addView(b);                    
        mainLayout.addView(ll);
    }
    scrollView.addView(mainLayout);
    setContentView(scrollView);
}

这篇关于快速添加多个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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