Reputation: 3
I'm very new to Android and I'm trying to dynamically add buttons in my android app, the problem is that they appear vertically, while this should be horizontally.
What I'm getting:
What I'm expecting (and want):
Code I'm using:
MainActivity.java:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout)findViewById(R.id.main_linearlayout);
for(int x = 1; x <= 5 ; x++)
{
LinearLayout tmpLinearLayout = new LinearLayout(this);
tmpLinearLayout.setOrientation(LinearLayout.VERTICAL);
tmpLinearLayout.setLayoutParams( new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f));
tmpLinearLayout.getLayoutParams().height = 200;
ll.addView(tmpLinearLayout);
for(int i = 0;i<5;i++)
{
Button tmpButton = new Button(this);
tmpButton.setText("nr:" + i +" - " + x);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, 1.0f);
tmpLinearLayout.addView(tmpButton, lp);
}
}
}
Layout (activity_main.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/main_linearlayout"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="@drawable/background"
android:orientation="horizontal" >
</LinearLayout>
Can anyone explain why it does this/correct me? Thank you!
Upvotes: 0
Views: 251
Reputation: 16526
You're programmatically setting vertical orientation.-
Replace this line
tmpLinearLayout.setOrientation(LinearLayout.VERTICAL);
with this one
tmpLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
PS: As far as I know, Horizontal
is the default orientation, so you actually could just delete the orientation line.
Upvotes: 1