Android开发Android知识Android进阶之路

ListView头布局为Listview时显示不全的问题解决

2017-08-08  本文已影响0人  暗尘随码去

开发中经常遇到各种较为复杂的界面,有Listview的头布局也是listview,嵌套ListView、ScrollView等,这些布局使用过程中经常会出现一个问题就是布局显示不全。今天就以解决listview的头布局也是listview时头布局显示不全时的解决方法做个笔记

问题:使用中发现listview的头布局也是listview时虽然在XML文件中设置了高为match_parent但却还是只展示了第一行

5B8E6C75-3447-4836-B9ED-8900E6AFAFE7.png

解决方法:自定义Listview重写onMeasure方法

public class ExpandListView extends ListView {

    public ExpandListView(Context context) {
        super(context);
    }

    public ExpandListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ExpandListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ExpandListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2
                , MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

参数Integer.MAX_VALUE >> 2何解?

在Android里面,一个控件所占的模式和大小是通过一个整数int来表示的,一个int类型我们知道有32 位。

D4A10FAC-D2B4-4F96-B5F4-0D378232A0A8.png

回头看我们的关键代码

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2
                , MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

效果图

650C32FB-7C86-4599-8F62-F3E6F7C3831F.png
上一篇 下一篇

猜你喜欢

热点阅读