如果高度为LayoutParams.WRAP_CONTENT,如何正确覆盖onMeasure()并给出最小高度

时间:2013-10-03 06:56:57

标签: android android-layout android-custom-view

我想在自定义onMeasure()中覆盖View方法。如果用户指定高度为LayoutParams.WRAP_CONTENT,那么我想给出一个特定的最小高度。现在,我的自定义View会占用WRAP_CONTENTMATCH_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); 
}

1 个答案:

答案 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); 
}