0

我想onMeasure()在我的自定义中覆盖方法View。如果用户指定高度,LayoutParams.WRAP_CONTENT那么我想给出一个特定的最小高度。现在,除非明确指定高度,否则我的自定义项会同时使用和View占据整个屏幕。当我在课堂上偶然发现这段代码时,我正在考虑签到:WRAP_CONTENTMATCH_PARENTLayoutParamsonMeasure()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); 
}
4

1 回答 1

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); 
}
于 2013-10-06T12:18:50.163 回答