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

oiopk7p5  于 2023-04-28  发布在  Android
关注(0)|答案(7)|浏览(197)

我需要在我的应用程序中动态更改ListView的高度。
有什么办法吗?

1dkrff03

1dkrff031#

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

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

muk1a3rh

muk1a3rh2#

用于动态更改高度和宽度,请尝试以下操作

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

也可以使用LayoutParams.FILL_PARENT或LayoutParams.WRAP_CONTENT代替height & width

rmbxnbpk

rmbxnbpk3#

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

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

设置列表视图高度的方法:

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);

希望对你有帮助。

ijnw1ujt

ijnw1ujt4#

首先要记住的是,当使用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;
        }
    };

现在height被固定为100。请注意,它是文本的高度,而不是视图本身的高度。所以在添加padding时请记住这一点。现在设置Adapter:

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来检查高度设置是否正确。这个解决方案对我很有效。希望这对你有帮助!!!!

eqqqjvef

eqqqjvef5#

你必须创建一个新的控件来扩展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

pkmbmrz7

pkmbmrz76#

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

fquxozlt

fquxozlt7#

使用自定义的列表视图,并给予高度作为wrap_content。

相关问题