Reputation: 37
is there any way to create a layout that wrap_content horizontally and if the line is full place the rest in new line(s).
example:
if I create a linear layout with orientation set to horizontal and then I create three buttons filling screen size(Button)(Button)(Button), now if I add more buttons it will be placed in a very ugly way in the end of the line. What I want is for the new buttons to be placed in new line, and I don't want to create more than one layout because these buttons are placed dynamically from java according to an API input. Is there anyway to do that, or I just have to design a function to handle it?
Upvotes: 0
Views: 520
Reputation: 1933
Think about GridView
, Refer to Android Developer
You should define grid view container in your_layout.xml
<your.package.ButtonsGridView
android:id="@+id/buttonsGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:stretchMode="columnWidth" />
Then extends GridView
to custom class named ButtonsGridView
,
and then extends ArrayAdapter<T>
to custom class named ButtonsAdapter
, to manager data.
And set ButtonsAdapter
to ButtonsGridView
ButtonsGridView buttonsGridView = (ButtonsGridView) findViewById(R.id.buttonsGridView);
ButtonsAdapter buttonsAdapter = new ButtonsAdapter(Context);
buttonsGridView.setAdapter(buttonsAdapter);
In consideration of different button width, you can manager width in adapter's method public View getView(int position, View convertView, ViewGroup parent)
, you can do anything you want to customize button.
Refer to this question&answerGrid View change column number runtime? to change column number.
Upvotes: 0
Reputation: 671
If your View
s are dynamically added maybe you want to use a GridView
because it use an Adapter
to obtain the View
s that will be displayed on screen (same as ListView
). But if you will add View
s to the Layout in Design time, maybe you can use GridLayout
Xamarin has a good explanation about GridLayout
check it here
Also you can check this question in SO to see a more detailed differences between the GridView
and the GridLayout
:
Upvotes: 1
Reputation: 26198
Well if your button have different width size then you can use GridView
where you set its android:numColumns
as auto_fit
where if first row is already filled with buttons then the next time you add a button will be added in the next line/row of the grid.
Lets say if you have a button with a width of match_parent
then the next button added will be on the next line, hence if you have a fixed button width then it will add the button next to each other until it filled the gridview width and the next button that will be added will be on the next line.
If you want to implement the gridview then you can go here.
Upvotes: 0