Android, how to place two relative layouts, one on

2019-07-24 00:24发布

In my Android App (for landscape screen orientation) I need to place widgets to two relative layouts, one on the left of the screen, and one at the right (to fill the full size).

I prefer working programmatically (I find it more flexible than xml).

Shoud I better use a TableLayout as the parent layout fro my sub-layouts?

2条回答
戒情不戒烟
2楼-- · 2019-07-24 00:44

Answering my own question:

Method suggested by alextsc didn't work, since RelativeLayouts (contrary to LinearLayouts) do not have any weight.

I did resolve with this (ugly :-() hack:

LinearLayout layoutContainer = new LinearLayout(myActivity.this);
layoutContainer.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

int width = getWindowManager().getDefaultDisplay().getWidth() / 2;

RelativeLayout layoutLeft = new RelativeLayout(Results.this);
layoutContainer.addView(layoutLeft, width, LayoutParams.FILL_PARENT);

RelativeLayout layoutRight = new RelativeLayout(Results.this);
layoutContainer.addView(layoutRight, width, LayoutParams.FILL_PARENT);
查看更多
闹够了就滚
3楼-- · 2019-07-24 00:52

For just two RelativeLayouts next to each other you have plenty of choice to archieve that. A horizontal LinearLayout would be the easiest in my opinion.


Edit: I never do layouts in code, but since you probably read a lot of docs with XML you should be able to translate this example. Uses a 50/50 space distribution for both layouts.

<LinearLayout android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:orientation="horizontal">
    <RelativeLayout android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1" >

    </RelativeLayout>

    <RelativeLayout android:layout_width="0dp"
                    android:layout_height="fill_parent"
                    android:layout_weight="1" >

    </RelativeLayout>

</LinearLayout>

Edit 2:

Definitely works, just tried this:

LinearLayout layoutContainer = new LinearLayout(this);
layoutContainer.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

// Arguments here: width, height, weight
LinearLayout.LayoutParams childLp = new LinearLayout.LayoutParams(0, LayoutParams.FILL_PARENT, 1);

RelativeLayout layoutLeft = new RelativeLayout(this);
layoutContainer.addView(layoutLeft, childLp);

RelativeLayout layoutRight = new RelativeLayout(this);
layoutContainer.addView(layoutRight, childLp);
查看更多
登录 后发表回答