我想让我的 LinearLayout 以所需的比例显示视图。我已经阅读了大约 10 或 15 个关于 LinearLayout 和 layout_weight 的其他问题,但由于某种原因,似乎没有答案适用于我的案例。我正在创建一个自定义 AlertDialog 颜色选择器,其中创建了一个自定义视图,如下所示:
private LinearLayout createLayout() {
//Create our top-level layout
LinearLayout mainLayout = new LinearLayout(mContext);
mainLayout.setOrientation(LinearLayout.VERTICAL);
mainLayout.setPadding(15, 0, 15, 0);
//Make the preset view at the top
LinearLayout.LayoutParams presetViewParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.2f);
mainLayout.addView(new PresetView(mContext), presetViewParams);
//Create another linear layout
LinearLayout subLayout = new LinearLayout(mContext);
subLayout.setOrientation(LinearLayout.HORIZONTAL);
subLayout.setPadding(0, 15, 0, 15);
//Add the Sat Lum View to the second layout
LinearLayout.LayoutParams satLumViewParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 0.60f);
subLayout.addView(new SatLumView(mContext), satLumViewParams);
//Add the divider between the sat lum view and the hue view
LinearLayout.LayoutParams dividerViewParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 0.1f);
subLayout.addView(new DividerView(mContext), dividerViewParams);
//Add the Hue View to the second layout
LinearLayout.LayoutParams hueViewParams = new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 0.30f);
subLayout.addView(new HueView(mContext), hueViewParams);
//Add the second layout to the first layout
LinearLayout.LayoutParams subLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.7f);
mainLayout.addView(subLayout, subLayoutParams);
//Add the Line view at the bottom of the main layout
LinearLayout.LayoutParams lineParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 0.1f);
mainLayout.addView(new LineView(mContext), lineParams);
//Return our completed layout
return mainLayout;
}
我遇到的问题是,尽管将我的三个垂直元素(PresetView、subLayout 和 LineView)的 layout_height 设置为0
,但权重仍然没有按照我想要的方式分配可用空间。subLayout 没有得到 70% 的空间,但总是更少。
据我所知,PresetView 总是获得尽可能多的垂直空间,而 subLayout 和 LineView 则保留了剩余的空间。这是我onMeasure()
的 PresetView 方法:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = resolveSize(250, widthMeasureSpec);
int height = resolveSize(150, heightMeasureSpec);
setMeasuredDimension(width, height);
}
250 和 150 是相当随意的值 - PresetView 旨在使用几乎任何尺寸集(因为我希望 LinearLayout 控制它的大小!)。
我的印象是使用 0 的 layout_height 并指定权重会使布局控制 View 占用的空间,而不是由 View 控制它。当我将它的 layout_height 设置为 0 时,为什么 PresetView 仍然占用完整的 150 像素?
其他 View的onMeasure()
方法与 PresetView 的方法相同,只是值不同。