Renjith
Renjith

Reputation: 3617

Programmatically position a button in relative layout

This is the layout XML I am using.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/tabTransparent"
    android:id="@+id/aLayoutRelative">

    <LinearLayout
        android:id="@+id/linearLayout8"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/linearLayout7"
        android:layout_below="@+id/linearLayout7"
        android:layout_marginTop="14dp" >

        <Button
            android:id="@+id/button5"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/text_accounts_aHistoryNotes" />
    </LinearLayout>

</RelativeLayout>

I want to add the button programmatically in java source. This is what I tried.

RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.aLayoutRelative);
LinearLayout lastLinearLayout = (LinearLayout)findViewById(R.id.linearLayout8);
lastLinearLayout.setOrientation(LinearLayout.HORIZONTAL);

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT,       LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.LEFT_OF, lastLinearLayout.getId());
layoutParams.addRule(RelativeLayout.BELOW, lastLinearLayout.getId());
layoutParams.setMargins(0, 14, 0, 0);
linearLayout.setLayoutParams(layoutParams);

Button button9 = new Button(this);
Log.i("tab0", recordTabs.get(0));
button9.setText(""+recordTabs.get(0));
button9.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
linearLayout.addView(button9);
relativeLayout.addView(linearLayout);

But in the view, the button is vertical with no text on it; aligned towards left of the page (in effect towards relative layout). XML version works well. I reckon the orientation settings turn out to be the culprit. Having googled in various documentations hardly helped.

Any thoughts?

Thanks in advance!

Upvotes: 2

Views: 7917

Answers (1)

Tamir Scherzer
Tamir Scherzer

Reputation: 1035

What are you trying to achieve?

for start, remove the

layoutParams.addRule(RelativeLayout.LEFT_OF, lastLinearLayout.getId());

so you can at least see the button below.

Why to you place the buttons in linear layouts?

Upvotes: 3

Related Questions