Android,如何放置两个相对布局,一个在左侧,一个在屏幕右侧?

时间:2011-08-14 09:34:01

标签: android layout

在我的Android应用程序中(用于横向屏幕方向)我需要将小部件放置到两个相对布局中,一个位于屏幕左侧,另一个位于右侧(以填充完整大小)。

我更喜欢以编程方式工作(我发现它比xml更灵活)。

Shoud我最好使用TableLayout作为子布局的父布局吗?

2 个答案:

答案 0 :(得分:10)

只有两个RelativeLayouts彼此相邻,你有很多选择来实现这一目标。在我看来,水平LinearLayout是最简单的。


编辑:我从不在代码中进行布局,但由于您可能已经阅读了大量使用XML的文档,因此您应该能够翻译此示例。对两种布局使用50/50的空间分布。

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

编辑2:

绝对有效,只是尝试了这个:

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

答案 1 :(得分:0)

回答我自己的问题:

alextsc建议的方法不起作用,因为RelativeLayouts(与LinearLayouts相反)没有任何重量。

我确实解决了这个问题(丑陋:-()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);