All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hadoopz.MyDroidLib.util.ListViewUtil Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2018 jw362j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hadoopz.MyDroidLib.util;

import android.widget.ListAdapter;
import android.widget.ListView;
import android.view.View;
import android.view.ViewGroup;

/**
 *
 * @author jw362j
 */
public class ListViewUtil {

    /**
     * 定义函数动态控制listView的高度
     * 在每次listView的adapter发生变化后,要调用setListViewHeightBasedOnChildren(listView)更新界面
     *
     * @param listView
     */
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        //获取listview的适配器

        ListAdapter listAdapter = listView.getAdapter(); //item的高度

        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0); //计算子项View 的宽高 //统计所有子项的总高度
            totalHeight += DisplayUtil.dip2px(listView.getContext(), listItem.getMeasuredHeight()) + listView.getDividerHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        params.height = totalHeight;
        listView.setLayoutParams(params);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy