开发者

Android, how to place two relative layouts, one on the left, and one on the right of the screen?

开发者 https://www.devze.com 2023-03-27 19:47 出处:网络
In my Android App (for landscape screen ori开发者_开发百科entation) 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).

In my Android App (for landscape screen ori开发者_开发百科entation) 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?


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);


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号