我想在自定义onMeasure()
中覆盖View
方法。如果用户指定高度为LayoutParams.WRAP_CONTENT
,那么我想给出一个特定的最小高度。现在,我的自定义View
会占用WRAP_CONTENT
和MATCH_PARENT
的整个屏幕,除非明确指定了高度。当我在LayoutParams
课程中偶然发现这段代码时,我正考虑在onMeasure()
中检查View
:
/**
* The layout parameters associated with this view and used by the parent
* {@link android.view.ViewGroup} to determine how this view should be
* laid out.
* {@hide}
*/
protected ViewGroup.LayoutParams mLayoutParams;
尽管受到保护,但在自定义View
类中无法访问它,注意到注释中的@hide
注释?虽然我可以通过调用public
方法getLayoutParams()
来解决此问题,但现在我想知道onMeasure()
是检查参数并指定最小高度值的正确位置吗?我目前的onMeasure()
看起来像这样。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final int height = getDefaultSize(getSuggestedMinimumHeight(),
heightMeasureSpec);
final int width = getDefaultSize(getSuggestedMinimumWidth(),
widthMeasureSpec);
int w = resolveSize(width, widthMeasureSpec);
int h = resolveSize(height, heightMeasureSpec);
setMeasuredDimension(w, h);
}
答案 0 :(得分:3)
我阅读了源代码并通过给resolveSize()
方法的最小宽度和最小高度解决了我的问题。这解决了我的问题:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int w = resolveSize(myMinWidth, widthMeasureSpec);
int h = resolveSize(myMinHeight, heightMeasureSpec);
setMeasuredDimension(w, h);
}