【问题标题】:How to change ListView height dynamically in Android?如何在 Android 中动态更改 ListView 高度?
【发布时间】:2011-05-20 11:15:35
【问题描述】:

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

有什么办法吗?

【问题讨论】:

    标签: android listview


    【解决方案1】:

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

    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类来改变listview的高度。

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

    取自here

    【讨论】:

    • 完美简化。谢谢
    • 谢谢,这对我也有用。实际上,我在滚动视图中以一种大形式使用 Listview。这就是为什么我必须在 listview 高度属性中使用此代码的其他 wrap wrap_content 值效果最好。无论如何,不​​错的实用程序好工作:)
    【解决方案2】:

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

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

    您也可以使用 LayoutParams.FILL_PARENT 或 LayoutParams.WRAP_CONTENT 代替高度和宽度

    【讨论】:

    • 这里的解决方案给了我一个转换错误,更改为 LinearLayout 效果很好。 LinearLayout.LayoutParams mParam = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,myList.size()*100); listViewPhone.setLayoutParams(mParam);
    • @Dr.Luiji 我用过类似RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, item.getRoutes().size() * 200); 的东西。但我无法从列表中看到某些项目。任何建议,我想显示列表的整个列表项。我能做什么?
    【解决方案3】:

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

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

    希望对你有所帮助。

    【讨论】:

    • 为什么要乘以500?执行“float px = 500 * (listView.getResources().getDisplayMetrics().density);”的原因是什么??
    【解决方案4】:

    首先要记住的是,在使用 mylistview.getmeasureheight 获取列表视图的高度时,它总是根据在适配器初始化期间设置的列表中的 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 来检查高度是否设置正确。这个解决方案对我有用。希望这有帮助!!!!!!

    【讨论】:

      【解决方案5】:

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

      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

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-10-07
            • 1970-01-01
            • 2014-08-07
            • 2012-09-25
            • 1970-01-01
            相关资源
            最近更新 更多