如何在Android中添加cycle中的按钮
我在应用程序中添加了一个按钮如何在Android中添加cycle中的按钮,android,Android,我在应用程序中添加了一个按钮 LayoutParams lpView = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); Button btn = new Button(this); btn.setText("Button"); linLayout.addView(btn, lpView); 但实际上我不知道我会有多少按钮,如何在循环中生成它。我的意思
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);
您可以使用纯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));
}
使用按钮数组
Button[] btnarray = new Button[length];
试着这样做:
你说不同的名字是什么意思?嗯,这个循环是用Android编写的,使用关键字FOR或WHILE。您可以使用任何集合来记住创建的按钮,也可以使用getChildAtindex在布局中直接访问它们。我真的不明白我们在这里面临着什么样的困难。请多解释。
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);
}