Make children of HorizontalScrollView as big as th

2019-07-03 12:05发布

问题:

The way I solved this problem is by creating a custom view for the child views, and then overriding onMeasure() for the custom view. The new onMeasure() sets the width and height to be as large as possible.

The problem is when you show the soft keyboard and rotate the phone. With the orientation change and the keyboard showing, onMeasure() sets the "largest" available height to be something ridiculously small, so when I hide the keyboard, the child views have the wrong size.

Is there a way to tell the views to recompute the layout when the keyboard goes away? Or am I doing onMeasure() wrong? Here's the code:

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

    int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    setMeasuredDimension(measureWidth(widthMeasureSpec), 
                         measureHeight(heightMeasureSpec));

    setLayoutParams(new LinearLayout.LayoutParams(
           measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec))
    );

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

public int measureWidth(int measureSpec) {
    int result = 0;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    Display display = ( (WindowManager)getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); 
    int screenWidth = display.getWidth();

    if (specMode == MeasureSpec.EXACTLY) {
        // We were told how big to be
        result = specSize;
    } else {
        // Measure the view
        result = screenWidth;
        if (specMode == MeasureSpec.AT_MOST) {
            // Respect AT_MOST value if that was what is called for by measureSpec
            result = Math.min(result, specSize);
        }
    }
    Log.d(TAG, "Width: "+String.valueOf(result));

    return result;
}

measureHeight() is done the same way.

回答1:

Your super.onMeasure(widthMeasureSpec, heightMeasureSpec) uses the passed in values I would think you would want these to be the actual measured width and height:

super.onMeasure(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec));