Android中如何动态改变ListView的高度?

发布于 2024-11-08 15:40:27 字数 59 浏览 0 评论 0原文

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

有什么办法可以做到这一点吗?

I need to change the height of a ListView dynamically in my app.

Is there any way to do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

梦归所梦 2024-11-15 15:40:27

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

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 中使用此实用程序类来更改列表视图高度。

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

取自此处

This piece of code helped me to achieve dynamic listview height.

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

In the main Activity use this Utility class to change the listview height.

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

Taken from here

失而复得 2024-11-15 15:40:27

要动态更改高度和宽度,请尝试此操作,

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

您也可以使用 LayoutParams.FILL_PARENT 或 LayoutParams.WRAP_CONTENT 而不是高度 &宽度

for change height and width dynamically so, try this

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

you can also use LayoutParams.FILL_PARENT or LayoutParams.WRAP_CONTENT instead of height & width

南街女流氓 2024-11-15 15:40:27

您可以使用下面的方法根据您的项目以编程方式设置列表视图的高度:

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

希望它会对您有所帮助。

You can use below method to set the height of listview programmatically as per your items:

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

Method used for setting height of 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;
        }

    }

Then set it like below code:

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

Hope it will help you.

风启觞 2024-11-15 15:40:27

首先要记住的是,在使用 mylistview.getmeasureheight 获取列表视图的高度时,它始终根据适配器初始化期间设置的列表内的文本视图/视图给出高度。所以我们需要如下声明适配器:

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

First thing to keep in mind is that while getting height of listview using mylistview.getmeasureheight, it always gives height according to the textview/View inside the list which was set during initializing of adapter. So we need to declare the adapter as follows:

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

Now height is fixed to 100. Note that it's the height of text and not the view itself. So keep it in mind when adding padding.
Now set the Adapter:

mylist.setAdapter(myadapter);

Now after every time you add an item to your list call a function as follows:

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

setListViewHeightBasedOnItems(mylist);

define the function in same class as:

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

}

You can also check if height is set or not correctly by returning true/false. This solution worked for me. Hope this Helps!!!!!

握住你手 2024-11-15 15:40:27

您必须创建一个新的控件来扩展列表视图,覆盖一些功能

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

You have to create a new control that extends the listview overwhriting some functions

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

沙与沫 2024-11-15 15:40:27

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

Personaly I spent so much time trying to find a solution, turns out all I had to do is to set my listview's height to wrap_content.

倦话 2024-11-15 15:40:27

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

use customized listview and give height as wrap_content.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文