2

I've written a custom view which I'd like to ensure is viewable on any screen size.

I've overridden the onMeasure:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);

    this.setMeasuredDimension(parentWidth, parentHeight);
}

and this seems to work fine when the view is smaller than the screen. Sometimes, though, the custom view is larger than the screen, and I'm planning for smaller screen sizes, so I wrapped the custom view in a ScrollView but now the parentHeight in the onMeasure comes out as 0.

I've changed the superclass of the custom view from View to ScrollView, hoping for an easy win of inheriting the scrolling functionality, but this hasn't happened so I'm left with trying to find a way of getting the ScrollView functionality to work with my custom view, or writing my own scrolling functionality.

Has anyone any advice? I've seen this post on Large Image Scrolling Using Low Level Touch Events and was going to copy some of that functionality if I'm forced to write my own, but would appreciate a nudge in the right direction either way.

4

1 回答 1

1

原来答案很简单。我离开ScrollView并改变了我的onMeasure。需要注意的是,虽然 Android 会提供宽度,但它不会为我提供高度,这最初是令人困惑的。为了让视图填充可用空间,我抓住了父视图的可见矩形。完整的代码(希望它会帮助遇到同样问题的其他人):

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight;

    if(isLandscape()) {
        Rect r = new Rect();
        ((ScrollView)getParent()).getGlobalVisibleRect(r);
        parentHeight = r.bottom - r.top;
    } else {
        parentHeight = (int) Util.getViewHeight();
    }

    this.setMeasuredDimension(parentWidth, parentHeight);
}
于 2011-07-20T18:07:27.087 回答