Make children of HorizontalScrollView as big as the screen?

强颜欢笑 提交于 2019-12-23 18:00: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));


来源:https://stackoverflow.com/questions/7420060/make-children-of-horizontalscrollview-as-big-as-the-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!