Reputation: 955
I am new with Android programming and using latest version of Android Studio.
I have a LinearLayout
and want to put 20 buttons programmatically.
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i<20;i++)
{
Button btn = new Button(this);
btn.setText("Button" + (i + 1));
btn.setTag(i + 1);
btn.setLayoutParams (new LinearLayout.LayoutParams(200, LinearLayout.LayoutParams.WRAP_CONTENT,1));
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), view.getTag().toString(), Toast.LENGTH_SHORT).show();
}
});
linearLayout.addView(btn);
}
I am using this code. It adds 20 buttons one under the other. However I want to place them like this:
Button1 Button2
Button3 Button4
...
Button19 Button20
Is it possible with LinearLayout
or should i use different type of layout?
Upvotes: 2
Views: 924
Reputation: 3975
You can't do this with just one LinearLayout.
To achieve this you must either use:
TableLayout, GridView, or (not ideal compared to these two) 2 Vertical LinearLayouts inside a Horizontal LinearLayout
Upvotes: 3
Reputation: 16537
It's not possible using single LinearLayout. You can use nested layouts so in your example Button1 and Button2 are in one horizontal layout and that layout is then added to larger vertical layout.
You can also use GridLayout - it was designed to handle your case easily.
Upvotes: 2