简体   繁体   中英

Dynamic button display programmatically Android

I want to add buttons programmatically on the screen and I am getting the value by parsing an API and now I want to display the buttons according to the length of an array. I am doing this but I am only getting the last button displayed, but inside the for loop I'm getting all values correct but displaying only the last button. This is my code:

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();
}

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

You mustn't give x and y values in Android.you can add buttom top left right of an item. Also layout parameters you should use wrap_content or fill_parent.

    Button button = new Button(this);
    button.setText(@"text");
    button.setLayoutParams(new LayoutParams(WRAP_CONTENT,WRAP_CONTENT));
    layout.addView(button);

I think the problem is with the relative layout. Your buttons might be getting stack on top of each other. Try making the parent a linear layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM