Reputation: 16821
I have the following method which I call a few times to create a list of buttons. It works well and creates the buttons.
public void CreateButton(int i) {
LinearLayout btnLayout = (LinearLayout)findViewById(R.id.btnLayout);
Button btn = new Button(this);
btn.setId(i);
btn.setText(String.valueOf(i+1));
btnLayout.addView(btn);
}
But each created button is fitting the screen in width, and I would want it to stay side by side, two buttons per row. I managed to set the button to half the screen size using this:
int displaywidth= getResources().getDisplayMetrics().widthPixels;
btn.setLayoutParams(new LayoutParams((int)(displaywidth/2), LayoutParams.WRAP_CONTENT));
It makes the button's width to be half the screen's size, but I can't figure out how to place them side by side. Any help is appreciated.
Upvotes: 0
Views: 956
Reputation: 13930
Change your orientation
in your LinearLayout
to horizontal
.
<LinearLayout
...
android:orientation="horizontal"
... >
...
</LinearLayout>
If you only have a single LinearLayout
that is to hold multiple side-by-side buttons you can make horizontal LinearLayout
s to hold your button pairs and either nest them in the main veritical
layout or utilize another layout, for example RelativeLayout
, to get the desired results.
Upvotes: 1
Reputation: 1226
One way to solve the problem is by using their weight and width. Make sure the Linear Layout has a horizontal orientation. Then, use Layout_params to set their width to "Wrap_Content" and their weight to "1". Then both will automatically take up the same amount of space.
Upvotes: 0
Reputation: 1661
Try using weight property of LinearLayout. If in each row you want only two buttons then give
android:weightSum="1"
to LinearLayout and
android:layout_weight="0.5"
to each button or you can set weight dynamically in your code by
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, xf);
where x represents the float value of layout weight of your button. for more details about layout weight http://developer.android.com/guide/topics/ui/layout/linear.html
Upvotes: 0