如何在Android中循环添加按钮

时间:2013-01-08 07:33:53

标签: android

我在我的应用程序中添加了一个按钮

LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        Button btn = new Button(this);
        btn.setText("Button");
        linLayout.addView(btn, lpView);

但实际上我不知道我有多少按钮,如何在循环中生成它。我的意思是,如何做不同的名字:

Button btn1 = new Button(this); 
Button btn2 = new Button(this); Button
btn3 = new Button(this);

3 个答案:

答案 0 :(得分:0)

您可以使用普通的Java数组按钮:

Button[] mButtonsArray = new Button[10];
        for (Button b : mButtonsArray) {
            b = new Button(this);
            linLayout.addView(b, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        }

答案 1 :(得分:0)

使用Button数组。

Button[] btnarray = new Button[length];

答案 2 :(得分:0)

尝试这种方式:

 public void GenerateButtons()
    {
    LinearLayout m_ll_layout;
    public static ArrayList<Button> m_arr_btn= new ArrayList<Button>();
    RelativeLayout p_rl_layout=new RelativeLayout(this);
    RelativeLayout.LayoutParams layoutParams = null;
    layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,        RelativeLayout.LayoutParams.WRAP_CONTENT);          
    m_ll_layout = new LinearLayout(m_context);
    m_ll_layout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    for (int i = 0; i < 10; i++)
    {
        Button m_btn = new Button(m_context);
        m_btn.setLayoutParams(new LinearLayout.LayoutParams(90, LayoutParams.WRAP_CONTENT));
        m_btn.setText("Button");
        m_btn.setId(i);
        m_btn.setOnClickListener(OnClickBtn_TimeListener);
        m_arr_btn.add(m_btn);
        m_ll_layout.addView(m_btn);         
    }
    layoutParams.addRule(RelativeLayout.BELOW);
    p_rl_layout.addView(m_ll_layout, layoutParams);
}