0

我想以编程方式在屏幕上添加按钮,我通过解析获得值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();
}
4

3 回答 3

2

A RelativeLayout will stack the views you add to it at the top-let corner if you don't specify some placement rules. Your buttons are added to the layout but they are placed one on top of each other and so the only visible is the last one you add. Here are some modification of your for loop:

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);
}
于 2012-04-13T08:20:01.253 回答
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);
于 2012-04-13T08:19:30.710 回答
0

我认为问题在于相对布局。您的按钮可能会堆叠在一起。尝试使父级成为线性布局。

于 2012-04-13T08:19:40.227 回答