listview 与 ScrollView 兼容写法, listview 自定义高度

兼容 listview 与 ScrollView ,  listview 自适应 高度 , 兼容 每个item 有任意行 


首先 , listview 需要自定义

public class MyListView extends ListView {

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

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

    public MyListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

}

xml 文件也不能使用默认的 listview , 写成如下:

                            <com.wang.joborderinquery.joborderinquery.MyListView
                                android:id="@+id/main_list_joiq"
                                android:layout_width="match_parent"
                                android:layout_height="match_parent"
                                android:layout_gravity="center"
                                android:fastScrollEnabled="true"
                                android:foregroundGravity="center"
                                android:scrollbarAlwaysDrawVerticalTrack="true">
                            </com.wang.joborderinquery.joborderinquery.MyListView>

java 页面 定义 listview 也用自己的

private MyListView main_list_joiq;

最后 添加 自定义高度 

        //根据实际情况调整listview的高度
        private void setListViewHeightBasedOnChildren(ListView mList) {
            // 获取ListView对应的Adapter
            ListAdapter listAdapter = mList.getAdapter();
            if (listAdapter == null) {
                return;
            }
            int totalHeight = 0;
            for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
                // listAdapter.getCount()返回数据项的数目
                View listItem = listAdapter.getView(i, null, mList);
                // 计算子项View 的宽高
                listItem.measure(0, 0);
                Log.e("ietm"+i,"==="+listItem.getMeasuredHeight());
                // 统计所有子项的总高度
                totalHeight += listItem.getMeasuredHeight();
            }
            ViewGroup.LayoutParams params = mList.getLayoutParams();
            params.height = totalHeight + (mList.getDividerHeight() * (listAdapter.getCount()-1));
            // listView.getDividerHeight()获取子项间分隔符占用的高度
            // params.height最后得到整个ListView完整显示需要的高度
            mList.setLayoutParams(params);
//            todat = System.currentTimeMillis();
        }


猜你喜欢

转载自blog.csdn.net/baichanna9833/article/details/80580943