我無法讓我的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的方法相同,只有不同的值。