Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Creating button dynamically and fill layout

I'm creating a button dynamically. The number of button is depend on the size of arraylist. the problem is, after creating the button I will add to the layout using addview method. The problem is I'm using linear layout, as by default orientation for linear layout is horizontal, so the button will fill the layout horizontally. Because of that some of the button is not visible. What I'm trying to achieve is something look like this

multiple button in android messaging contact

My code is like below:

Button[] tv = new Button[arraylist.size()];
for(int i=0;i<arraylist.size();i++){                                
    tv[i] = new Button(getApplicationContext());
    tv[i].setText(arraylist.get(i).toString());
    tv[i].setTextColor(Color.parseColor("#000000"));
    tv[i].setTextSize(20);
    tv[i].setPadding(15, 5, 15, 5);     
    linearlayout.addView(tv[i]);    
}

If I set the orientation of linear layout to vertical the button will fill vertically. So if there any solution to create the button dynamically and fill the layout both horizontal and vertical as shown by image.

like image 490
Zahary Avatar asked Dec 12 '22 06:12

Zahary


1 Answers

There is not a canned layout in the SDK that does exactly what you are aiming for (i.e. lay out as many children horizontally as will fit, then flow to the next line to lay out some more), so you will need to create a custom ViewGroup that accomplishes this purpose. Luckily for you, Romain Guy created one live on-screen during a presentation at Devoxx.

Here is a link to that presentation video.

Here is a link to the sample code and slides.

HTH

like image 122
devunwired Avatar answered Jan 06 '23 18:01

devunwired