android-ui - Android 如何仅在内容占满屏幕高度时滚动,未占满高度时居中?
伊谢尔伦
伊谢尔伦 2017-04-17 14:55:46
[Android讨论组]

如下图所示:

Card content 中的内容数量不固定。Card header 和 Card footer 内容固定。

想要在内容较少而屏幕较高(图1)时,将内容全部显示,整个 Card 竖直居中于屏幕。

而内容较多而屏幕较小(图2),内容无法一屏显示完整时,让 Card 占满屏幕,而 Card content 部分利用 ScrollView 来显示内容。

有没有什么优雅简洁的方法可以做到?如果要自己实现一个 View 来做到的话,有什么大致的思路可供参考吗?

谢谢。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
怪我咯

Mariotaku 大神已经帮我解决了这个问题。根据他写的思路我整理了一下:

首先我把一个撑满整个屏幕的 RelativeLayout 的 gravity 设为 center,然后整个 card 放在里面自然居中。Card 里面放三个 View,分别是 header,中间的 ScrollView 和 footer。

Card 部分自己实现,且称之为 CardLayout:

class CardLayout extends ViewGroup {

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

        int w = MeasureSpec.getSize(widthMeasureSpec);
        int h = MeasureSpec.getSize(heightMeasureSpec);

        // measure 一下 card header
        measureChild(getChildAt(0), widthMeasureSpec, heightMeasureSpec);
        // measure 一下 card footer
        measureChild(getChildAt(2), widthMeasureSpec, heightMeasureSpec);

        // 计算 card content 部分最大可占用的高度
        int cardMaxHeight = h - getChildAt(0).getMeasuredHeight() - getChildAt(2).getMeasuredHeight();

        // measure 一下 card content
        measureChild(getChildAt(1), getChildMeasureSpec(widthMeasureSpec, 0, w), getChildMeasureSpec(MeasureSpec.makeMeasureSpec(cardMaxHeight, MeasureSpec.AT_MOST), 0, cardMaxHeight));

        // 整个 card 的高度
        setMeasuredDimension(w, getChildAt(0).getMeasuredHeight() + getChildAt(1).getMeasuredHeight() + getChildAt(2).getMeasuredHeight());

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // 将三个 child 分别 layout
        getChildAt(0).layout(0, 0, getChildAt(0).getMeasuredWidth(), getChildAt(0).getMeasuredHeight());
        getChildAt(1).layout(0, getChildAt(0).getBottom(), getChildAt(1).getMeasuredWidth(), getChildAt(0).getBottom() + getChildAt(1).getMeasuredHeight());
        getChildAt(2).layout(0, getChildAt(1).getBottom(), getChildAt(2).getMeasuredWidth(), getChildAt(1).getBottom() + getChildAt(2).getMeasuredHeight());
    }
        
}
PHP中文网

厉害,过来膜拜一下了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号