-2

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

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);
4

3 回答 3

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));
        }
于 2013-01-08T07:37:58.747 回答
0

使用 Button 数组。

Button[] btnarray = new Button[length];
于 2013-01-08T07:38:38.963 回答
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);
}
于 2013-01-08T07:52:18.583 回答