Android 以编程方式显示动态按钮
我想以编程方式在屏幕上添加按钮,通过解析Android 以编程方式显示动态按钮,android,android-layout,android-button,Android,Android Layout,Android Button,我想以编程方式在屏幕上添加按钮,通过解析API获得值,现在我想根据数组的长度显示按钮。我正在这样做,但我只显示最后一个按钮,但在for循环中,我得到的所有值都正确,但只显示最后一个按钮。这是我的代码: RelativeLayout relate; //... relate = (RelativeLayout)findViewById(R.id.relative); protected void onPostExecute(Void result) { if(dialog.isShow
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();
}
RelativeLayout relative;
//...
relate=(RelativeLayout)findViewById(R.id.relative);
受保护的void onPostExecute(void结果){
if(dialog.isShowing()==true){
dialog.dismise();
}
//内部宽度=100,高度=50,x=10,y=20;
对于(int i=0;i您不能在Android中给出x和y值。您可以在项目的左上角添加按钮。此外,布局参数您应该使用换行内容或填充父项
Button button = new Button(this);
button.setText(@"text");
button.setLayoutParams(new LayoutParams(WRAP_CONTENT,WRAP_CONTENT));
layout.addView(button);
我认为问题在于相对布局。您的按钮可能会堆叠在一起。请尝试将父级设置为线性布局。aRelativeLayout
会将您添加到其中的视图堆叠在顶部的左上角,如果您不指定某些放置规则。您的按钮会添加到布局中,但它们会放置在一个上下角相互重叠,因此唯一可见的是您添加的最后一个。以下是对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);
}
RelativeLayout relate;relate=(RelativeLayout)findViewById(R.id.relative);
for(int i=0;i0){
lp.addRule(RelativeLayout.down,b1.getId()-1);
}
b1.设置布局参数(lp);
相关。添加视图(b1);
}
0k让我来做,很快会回复您