【发布时间】:2011-10-26 17:32:55
【问题描述】:
在我的 Android 应用程序(横向屏幕方向)中,我需要将小部件放置到两个相对布局中,一个在屏幕左侧,一个在右侧(以填充整个尺寸)。
我更喜欢以编程方式工作(我发现它比 xml 更灵活)。
我应该更好地使用 TableLayout 作为子布局的父布局吗?
【问题讨论】:
在我的 Android 应用程序(横向屏幕方向)中,我需要将小部件放置到两个相对布局中,一个在屏幕左侧,一个在右侧(以填充整个尺寸)。
我更喜欢以编程方式工作(我发现它比 xml 更灵活)。
我应该更好地使用 TableLayout 作为子布局的父布局吗?
【问题讨论】:
对于两个相邻的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);
【讨论】:
回答我自己的问题:
alextsc 建议的方法不起作用,因为相对布局(与线性布局相反)没有任何权重。
我确实解决了这个问题(丑陋的:-() 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);
【讨论】: