我想在屏幕上以编程方式添加按钮,我通过解析API
来获取值,现在我想根据数组的长度显示按钮。我这样做但是我只显示最后一个按钮,但在for
循环内我得到的所有值都正确但只显示最后一个按钮。这是我的代码:
RelativeLayout relate;
//...
relate = (RelativeLayout)findViewById(R.id.relative);
protected void onPostExecute(Void result) {
if(dialog.isShowing() == true) {
dialog.dismiss();
}
//int width = 100, height =50, x = 10, y = 20;
for (int i =0;i<adapt_obj.city_name_array.length;i++){
b1 = new Button(myref);
b1.setText(adapt_obj.city_name_array[i]);
relate.addView(b1);
//relate.addView(b1, i, new RelativeLayout.LayoutParams(width,height));
//height = height+80;
}
listlocation.setAdapter(adapt_obj);
adapt_obj.notifyDataSetChanged();
}
答案 0 :(得分:2)
如果您未指定某些展示位置规则,则RelativeLayout
会将您在顶部角落添加的视图堆叠起来。您的按钮被添加到布局中,但它们一个放在另一个上面,因此唯一可见的是您添加的最后一个。以下是对for
循环的一些修改:
RelativeLayout relate; relate = (RelativeLayout)findViewById(R.id.relative);
for (int i = 0; i < adapt_obj.city_name_array.length; i++){
Button b1 = new Button(myref);
b1.setId(100 + i);
b1.setText(adapt_obj.city_name_array[i]);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
lp.addRule(RelativeLayout.BELOW, b1.getId() - 1);
}
b1.setLayoutParams(lp);
relate.addView(b1);
}
答案 1 :(得分:0)
您不能在Android中提供x和y值。您可以在项目的左上角添加按钮。另外布局参数应该使用wrap_content或fill_parent。
Button button = new Button(this);
button.setText(@"text");
button.setLayoutParams(new LayoutParams(WRAP_CONTENT,WRAP_CONTENT));
layout.addView(button);
答案 2 :(得分:0)
我认为问题在于相对布局。您的按钮可能会堆叠在一起。尝试使父级线性布局。