我有Activity
,会显示由2部分组成的自定义视图。我希望一部分是可见屏幕高度的1/3,另一部分是2/3。
我可以覆盖onMeasure()
并使用显示指标来查找显示的高度,但这并不考虑电池条或视图标题大小。
DisplayMetrics dm = new DisplayMetrics();
((WindowManager)contxt.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
int height = dm.heightPixels;
如何判断可显示区域的高度?我准备覆盖layout
或其他什么。 Android
的最佳做法是什么?我已经看到了这条线上的其他问题,但它们尚无定论。
答案 0 :(得分:1)
我想出了办法。我重写RelativeLayout,并让它保持指向我的上下视图的指针。然后当它处理onMeasure时,它会在我的2个视图上设置所需的高度。它们在处理onMeasure时使用所需的高度。这给了我一个可见区域的2/3视图,下面是另一个视图。
- 来自我的布局类
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// set default screen heights
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if ( upper != null )
upper.setPrefHeight((heightSize*2)/3);
if ( lower != null )
lower.setPrefHeight(heightSize/3);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
- 来自View派生类
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
/**
* Determines the width of this view
* @param measureSpec A measureSpec packed into an int
* @return The width of the view, honoring constraints from measureSpec
*/
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
DisplayMetrics dm = new DisplayMetrics();
((WindowManager)contxt.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
result = dm.widthPixels;
}
width = result;
return result;
}
/**
* Determines the height of this view
* @param measureSpec A measureSpec packed into an int
* @return The height of the view, honoring constraints from measureSpec
*/
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
result = prefHeight;
}
height = result;
return result;
}