如何在Android中动态更改ListView高度?

时间:2011-05-20 11:15:35

标签: android listview

我需要在我的应用中动态更改ListView的高度。

有没有办法做到这一点?

7 个答案:

答案 0 :(得分:24)

这段代码帮助我实现了动态列表视图高度。

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

public class Utility {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
}

在主Activity中使用此Utility类更改列表视图高度。

 phraseListView=(ListView)findViewById(R.id.phrase_listview);
 phraseAdapter=new PhraseListAdapter(this);
 phraseListView.setAdapter(phraseAdapter);
 Utility.setListViewHeightBasedOnChildren(phraseListView);

取自here

答案 1 :(得分:8)

动态改变高度和宽度,试试这个

RelativeLayout.LayoutParams mParam = new RelativeLayout.LayoutParams((int)(width),(int)(height);
        listView.setLayoutParams(mParam);

你也可以使用LayoutParams.FILL_PARENT或LayoutParams.WRAP_CONTENT而不是height&amp;宽度

答案 2 :(得分:6)

您可以使用以下方法根据您的项目以编程方式设置listview的高度:

<ListView
        android:id="@+id/lvMenu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffff"
        />

用于设置listview高度的方法:

public static boolean setListViewHeightBasedOnItems(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter != null) {

            int numberOfItems = listAdapter.getCount();

            // Get total height of all items.
            int totalItemsHeight = 0;
            for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
                View item = listAdapter.getView(itemPos, null, listView);
                float px = 500 * (listView.getResources().getDisplayMetrics().density);
                item.measure(View.MeasureSpec.makeMeasureSpec((int)px, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                totalItemsHeight += item.getMeasuredHeight();
            }

            // Get total height of all item dividers.
            int totalDividersHeight = listView.getDividerHeight() *
                    (numberOfItems - 1);
            // Get padding
            int totalPadding = listView.getPaddingTop() + listView.getPaddingBottom();

            // Set list height.
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalItemsHeight + totalDividersHeight + totalPadding;
            listView.setLayoutParams(params);
            listView.requestLayout();
            return true;

        } else {
            return false;
        }

    }

然后设置如下代码:

MenuAdapter menuAdapter = new MenuAdapter(context, R.layout.menu_item);
            lvMenu.setAdapter(menuAdapter);
            setListViewHeightBasedOnItems(lvMenu);

希望它会对你有所帮助。

答案 3 :(得分:1)

首先要记住的是,在使用mylistview.getmeasureheight获取listview的高度时,它总是根据在初始化适配器期间设置的列表中的textview / View给出高度。所以我们需要按如下方式声明适配器:

myadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myarraylist){
        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView textView = ((TextView) view.findViewById(android.R.id.text1));
            textView.setMinHeight(0); // Min Height
            textView.setMinimumHeight(0); // Min Height
            textView.setHeight(100); // Height
            return view;
        }
    };

现在高度固定为100.请注意,它是文本的高度而不是视图本身。所以在添加填充时请记住这一点。 现在设置适配器:

mylist.setAdapter(myadapter);

现在,每次向列表中添加项目后,请按以下方式调用函数:

myarraylist.add(ds.getKey());
myadapter.notifyDataSetChanged();
mylist.setAdapter(myadapter);

setListViewHeightBasedOnItems(mylist);

在同一个类中定义函数:

public static boolean setListViewHeightBasedOnItems(ListView listView) {

    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter != null) {

        int numberOfItems = listAdapter.getCount();

        // Get total height of all items.
        int totalItemsHeight = 0;
        for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
            View item = listAdapter.getView(itemPos, null, listView);
            float px = 500 * (listView.getResources().getDisplayMetrics().density);
            item.measure(View.MeasureSpec.makeMeasureSpec((int)px, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            totalItemsHeight += item.getMeasuredHeight();
        }

        // Get total height of all item dividers.
        int totalDividersHeight = listView.getDividerHeight() *
                (numberOfItems - 1);
        // Get padding
        int totalPadding = listView.getPaddingTop() + listView.getPaddingBottom();

        // Set list height.
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalItemsHeight + totalDividersHeight + totalPadding;
        listView.setLayoutParams(params);
        listView.requestLayout();
        return true;

    } else {
        return false;
    }

}

您还可以通过返回true / false来检查高度是否设置正确。这个解决方案对我有用。希望这有助于!!!!!

答案 4 :(得分:1)

您必须创建一个新控件以扩展listview而不覆盖某些功能

public class WrapContentListView extends ListView {
    public WrapContentListView(Context context) {
        super(context);
    }

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

    public WrapContentListView(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);
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        super.setAdapter(adapter);
        setHeightWrapContent();
    }

    public void setHeightWrapContent() {
        ListAdapter listAdapter = getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, this);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = this.getLayoutParams();

        params.height = totalHeight
                + (this.getDividerHeight() * (listAdapter.getCount() - 1));
        this.setLayoutParams(params);
    }
}

https://github.com/mzlogin/WrapContentListView/blob/master/app/src/main/java/org/mazhuang/wrapcontentlistview/WrapContentListView.java

答案 5 :(得分:0)

我个人花了很多时间试图找到一个解决方案,结果我要做的就是将列表视图的高度设置为wrap_content。

答案 6 :(得分:-1)

使用自定义列表视图并将高度设为wrap_content。