我无法让我的LinearLayout以所需的比例显示视图。我已经仔细阅读了关于LinearLayout和layout_weight的其他10或15个问题,但出于某种原因,似乎没有答案适用于我的案例。我创建一个自定义AlertDialog颜色选择器与作为创建自定义视图如下:使用嵌套的LinearLayout时Layout_weight不能正常工作
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来控制它的大小! )。我的印象是,使用layout_height为0并指定权重将布局控制在视图占用的空间中,而不是视图控制它。为什么PresetView仍然占用150像素,当我将layout_height设置为0时?
其他视图的onMeasure()方法与PresetView的方法相同,只有不同的值。