0

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

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

1 Comment

0k let me do and will reply u soon

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.