代码之家  ›  专栏  ›  技术社区  ›  DougW

如何将ListView放入ScrollView而不使其折叠?

  •  341
  • DougW  · 技术社区  · 15 年前

    我到处寻找这个问题的解决办法,我能找到的唯一答案似乎是 don't put a ListView into a ScrollView ". 我还没有看到任何真正的解释 为什么?

    所以问题是,如何将ListView放置到ScrollView中而不将其折叠到最小高度?

    27 回复  |  直到 10 年前
        1
  •  198
  •   Muhammad Babar    9 年前

    ListView 使它不滚动是极其昂贵的,并违背了整个目的 . 你应该 不是 做这个。就用一个 LinearLayout 相反。

        2
  •  263
  •   Reaz Murshed vir us    9 年前

    这是我的解决办法。我对Android平台还比较陌生,我敢肯定这有点不切实际,尤其是关于call.measure的部分,直接测量,设置 LayoutParams.height 但它是有效的。

    你只要打个电话 Utility.setListViewHeightBasedOnChildren(yourListView) 它将调整大小,以完全适应其项目的高度。

    public class Utility {
        public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                // pre-condition
                return;
            }
    
            int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
    
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                if (listItem instanceof ViewGroup) {
                    listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                 }
    
                 listItem.measure(0, 0);
                 totalHeight += listItem.getMeasuredHeight();
            }
    
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
        }
    }
    
        3
  •  89
  •   Atul Bhardwaj    11 年前

    这肯定有用。。。。。。。。。。。。
    <ScrollView ></ScrollView> 在布局XML文件中 Custom ScrollView 喜欢 <com.tmd.utils.VerticalScrollview > </com.tmd.utils.VerticalScrollview >

    package com.tmd.utils;
    
    import android.content.Context;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.MotionEvent;
    import android.widget.ScrollView;
    
    public class VerticalScrollview extends ScrollView{
    
        public VerticalScrollview(Context context) {
            super(context);
        }
    
         public VerticalScrollview(Context context, AttributeSet attrs) {
                super(context, attrs);
            }
    
            public VerticalScrollview(Context context, AttributeSet attrs, int defStyle) {
                super(context, attrs, defStyle);
            }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            final int action = ev.getAction();
            switch (action)
            {
                case MotionEvent.ACTION_DOWN:
                        Log.i("VerticalScrollview", "onInterceptTouchEvent: DOWN super false" );
                        super.onTouchEvent(ev);
                        break;
    
                case MotionEvent.ACTION_MOVE:
                        return false; // redirect MotionEvents to ourself
    
                case MotionEvent.ACTION_CANCEL:
                        Log.i("VerticalScrollview", "onInterceptTouchEvent: CANCEL super false" );
                        super.onTouchEvent(ev);
                        break;
    
                case MotionEvent.ACTION_UP:
                        Log.i("VerticalScrollview", "onInterceptTouchEvent: UP super false" );
                        return false;
    
                default: Log.i("VerticalScrollview", "onInterceptTouchEvent: " + action ); break;
            }
    
            return false;
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent ev) {
            super.onTouchEvent(ev);
            Log.i("VerticalScrollview", "onTouchEvent. action: " + ev.getAction() );
             return true;
        }
    }
    
        4
  •  25
  •   Catalina    10 年前

    ListView 内部 ScrollView ,我们可以使用 作为一个 卷轴视图 . 必须在 列表视图 列表视图 . 顶部和底部的其他布局 可以通过将布局添加到的页眉和页脚来放置 . 所以整个 列表视图 会给你一个滚动的体验。

        5
  •  21
  •   djunod    12 年前

    大量

    以下是基于道格建议的代码。。。在片段中工作,占用更少的内存。

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, view, listView);
            if (i == 0) {
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, LayoutParams.WRAP_CONTENT));
            }
            view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
    

    对每个嵌入的listview调用setListViewHeightBasedOnChildren(listview)。

        6
  •  17
  •   Jason Y    10 年前

    ListView实际上已经能够测量自身的高度,使其足以显示所有项目,但当您仅指定wrap\u内容时,它就不能做到这一点(测量等级未指定). 当给定一个高度最多测量. 有了这些知识,您就可以创建一个非常简单的子类来解决这个问题,它比上面发布的任何解决方案都要好得多。您仍然应该对这个子类使用wrap\u内容。

    public class ListViewForEmbeddingInScrollView extends ListView {
        public ListViewForEmbeddingInScrollView(Context context) {
            super(context);
        }
    
        public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public ListViewForEmbeddingInScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 4, MeasureSpec.AT_MOST));
        }
    }
    

    用非常大的尺寸操纵高度测量仪,使其最大值为(Integer.MAX\u值>gt;4)使ListView测量给定(非常大)高度的所有子级,并相应地设置其高度。

    这比其他解决方案效果更好,原因如下:

    1. 它能正确测量所有东西(填充物、分隔物)
    2. 由于#2的原因,它可以正确处理宽度或项目数的更改,而无需任何附加代码

    不利的一面是,您可能会认为这样做依赖于SDK中未记录的行为,这可能会改变。另一方面,您可能会认为wrap\u内容实际上应该如何与ListView一起工作,而当前的wrap\u内容行为只是被破坏了。

    如果您担心行为将来可能会发生变化,那么只需将onMeasure函数和相关函数从ListView.java 并进入您自己的子类,然后使通过onMeasure的最多路径也为UNSPECIFIED运行。

        7
  •  13
  •   TalkLittle    11 年前

    它有一个内置的设置。在滚动视图上:

    android:fillViewport="true"
    

    在爪哇,

    mScrollView.setFillViewport(true);
    

    http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/

        8
  •  10
  •   Dedaniya HirenKumar    9 年前

    您可以创建不可滚动的自定义ListView

    public class NonScrollListView extends ListView {
    
        public NonScrollListView(Context context) {
            super(context);
        }
        public NonScrollListView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
        public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                        Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
                ViewGroup.LayoutParams params = getLayoutParams();
                params.height = getMeasuredHeight();    
        }
    }
    

    在布局资源文件中

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    
        <!-- com.Example Changed with your Package name -->
    
        <com.Example.NonScrollListView
            android:id="@+id/lv_nonscroll_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </com.Example.NonScrollListView>
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/lv_nonscroll_list" >
    
            <!-- Your another layout in scroll view -->
    
        </RelativeLayout>
    </RelativeLayout>
    

    在Java文件中

    创建customListview的对象,而不是ListView,如:

        9
  •  8
  •   Ashish Saini    11 年前

    我们不能使用两个滚动同时,我们将获取ListView的总长度并用总高度展开ListView。然后我们可以直接在ScrollView中添加ListView,或者使用LinearLayout,因为ScrollView直接有一个子级。 在代码中复制setListViewHeightBasedOnChildren(lv)方法并展开listview,然后可以在scrollview中使用listview。

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
     <ScrollView
    
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
             android:background="#1D1D1D"
            android:orientation="vertical"
            android:scrollbars="none" >
    
            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#1D1D1D"
                android:orientation="vertical" >
    
                <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="40dip"
                    android:background="#333"
                    android:gravity="center_vertical"
                    android:paddingLeft="8dip"
                    android:text="First ListView"
                    android:textColor="#C7C7C7"
                    android:textSize="20sp" />
    
                <ListView
                    android:id="@+id/first_listview"
                    android:layout_width="260dp"
                    android:layout_height="wrap_content"
                    android:divider="#00000000"
                   android:listSelector="#ff0000"
                    android:scrollbars="none" />
    
                   <TextView
                    android:layout_width="fill_parent"
                    android:layout_height="40dip"
                    android:background="#333"
                    android:gravity="center_vertical"
                    android:paddingLeft="8dip"
                    android:text="Second ListView"
                    android:textColor="#C7C7C7"
                    android:textSize="20sp" />
    
                <ListView
                    android:id="@+id/secondList"
                    android:layout_width="260dp"
                    android:layout_height="wrap_content"
                    android:divider="#00000000"
                    android:listSelector="#ffcc00"
                    android:scrollbars="none" />
      </LinearLayout>
      </ScrollView>
    
       </LinearLayout>
    

    活动类中的onCreate方法:

     import java.util.ArrayList;
      import android.app.Activity;
     import android.os.Bundle;
     import android.view.Menu;
     import android.view.View;
     import android.view.ViewGroup;
     import android.widget.ArrayAdapter;
     import android.widget.ListAdapter;
      import android.widget.ListView;
    
       public class MainActivity extends Activity {
    
       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listview_inside_scrollview);
        ListView list_first=(ListView) findViewById(R.id.first_listview);
        ListView list_second=(ListView) findViewById(R.id.secondList);
        ArrayList<String> list=new ArrayList<String>();
        for(int x=0;x<30;x++)
        {
            list.add("Item "+x);
        }
    
           ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), 
              android.R.layout.simple_list_item_1,list);               
          list_first.setAdapter(adapter);
    
         setListViewHeightBasedOnChildren(list_first);
    
          list_second.setAdapter(adapter);
    
        setListViewHeightBasedOnChildren(list_second);
       }
    
    
    
       public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
    
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
    
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
          }
    
        10
  •  6
  •   JackA    9 年前

    这是唯一对我有用的东西:

    你可以用棒棒糖

    yourtListView.setNestedScrollingEnabled(true);
    

    如果你需要向后兼容旧版本的操作系统,你必须使用RecyclerView。

        11
  •  4
  •   Cheryl Simon    15 年前

    滚动视图。所以这就像把一个ScrollView放到一个ScrollView中。

    你想完成什么?

        12
  •  4
  •   Abandoned Cart    12 年前

    这是道格、好人格雷格和保罗的答案组合。我发现,在尝试将其与自定义listview适配器和非标准列表项一起使用时,这一切都是必需的,否则listview会使应用程序崩溃(也会导致Nex的答案崩溃):

    public void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                return;
            }
    
            int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                if (listItem instanceof ViewGroup)
                    listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
    
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
        }
    
        13
  •  3
  •   Phil Ryan    11 年前

    我改了@道格的 Utility 变成C#(用于Xamarin)。对于列表中的固定高度项目,下面的方法可以很好地工作,如果只有一些项目比标准项目大一点,那么基本上是可以的,或者至少是一个好的开始。

    // You will need to put this Utility class into a code file including various
    // libraries, I found that I needed at least System, Linq, Android.Views and 
    // Android.Widget.
    using System;
    using System.Linq;
    using Android.Views;
    using Android.Widget;
    
    namespace UtilityNamespace  // whatever you like, obviously!
    {
        public class Utility
        {
            public static void setListViewHeightBasedOnChildren (ListView listView)
            {
                if (listView.Adapter == null) {
                    // pre-condition
                    return;
                }
    
                int totalHeight = listView.PaddingTop + listView.PaddingBottom;
                for (int i = 0; i < listView.Count; i++) {
                    View listItem = listView.Adapter.GetView (i, null, listView);
                    if (listItem.GetType () == typeof(ViewGroup)) {
                        listItem.LayoutParameters = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
                    }
                    listItem.Measure (0, 0);
                    totalHeight += listItem.MeasuredHeight;
                }
    
                listView.LayoutParameters.Height = totalHeight + (listView.DividerHeight * (listView.Count - 1));
            }
        }
    }
    

    谢谢@DougW,这让我摆脱了一个困境,当我不得不与其他人的代码。:-)

        14
  •  3
  •   Shashank Kapsime    8 年前

    在这不可能之前。但是随着新Appcompat库和设计库的发布,这一点可以实现。

    https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html

    我不知道它是否可以与Listview一起使用,但可以与RecyclerView一起使用。

    代码段:

    <android.support.v4.widget.NestedScrollView 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    
    </android.support.v4.widget.NestedScrollView>
    
        15
  •  2
  •   PSchuette    11 年前

    db = new dbhelper(this);
    
     cursor = db.dbCursor();
    int count = cursor.getCount();
    if (count > 0)
    {    
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.layoutId);
    startManagingCursor(YOUR_CURSOR);
    
    YOUR_ADAPTER(**or SimpleCursorAdapter **) adapter = new YOUR_ADAPTER(this,
        R.layout.itemLayout, cursor, arrayOrWhatever, R.id.textViewId,
        this.getApplication());
    
    int i;
    for (i = 0; i < count; i++){
      View listItem = adapter.getView(i,null,null);
      linearLayout.addView(listItem);
       }
    }
    

    notifyDataSetChanged(); 不会像预期的那样工作,因为视图不会被重新绘制。 如果你需要解决的话就这么做

    adapter.registerDataSetObserver(new DataSetObserver() {
    
                @Override
                public void onChanged() {
                    super.onChanged();
                    removeAndRedrawViews();
    
                }
    
            });
    
        16
  •  2
  •   Ali    11 年前

    在ScrollView中使用ListView有两个问题。

    1-ListView必须完全扩展到其子级高度。此列表视图解决了以下问题:

    public class ListViewExpanded extends ListView
    {
        public ListViewExpanded(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            setDividerHeight(0);
        }
    
        @Override
        public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST));
        }
    }
    

    分隔线高度必须为0,请改用行填充。

    2-ListView使用触摸事件,因此ScrollView不能像往常一样滚动。此滚动视图可解决此问题:

    public class ScrollViewInterceptor extends ScrollView
    {
        float startY;
    
        public ScrollViewInterceptor(Context context, AttributeSet attrs)
        {
            super(context, attrs);
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent e)
        {
            onTouchEvent(e);
            if (e.getAction() == MotionEvent.ACTION_DOWN) startY = e.getY();
            return (e.getAction() == MotionEvent.ACTION_MOVE) && (Math.abs(startY - e.getY()) > 50);
        }
    }
    

    这是我找到的最好的方法!

        17
  •  2
  •   brokedid    10 年前

    我使用的一个解决方案是,将ScrollView的所有内容(应该在listView的上面和下面)添加为listView中的headerView和footerView。

        18
  •  1
  •   Community Mohan Dere    8 年前

    多亏了 Vinay's code 这里是我的代码,当你不能在一个滚动视图中有一个列表视图,但你需要这样的东西

    LayoutInflater li = LayoutInflater.from(this);
    
                    RelativeLayout parent = (RelativeLayout) this.findViewById(R.id.relativeLayoutCliente);
    
                    int recent = 0;
    
                    for(Contatto contatto : contatti)
                    {
                        View inflated_layout = li.inflate(R.layout.header_listview_contatti, layout, false);
    
    
                        inflated_layout.setId(contatto.getId());
                        ((TextView)inflated_layout.findViewById(R.id.textViewDescrizione)).setText(contatto.getDescrizione());
                        ((TextView)inflated_layout.findViewById(R.id.textViewIndirizzo)).setText(contatto.getIndirizzo());
                        ((TextView)inflated_layout.findViewById(R.id.textViewTelefono)).setText(contatto.getTelefono());
                        ((TextView)inflated_layout.findViewById(R.id.textViewMobile)).setText(contatto.getMobile());
                        ((TextView)inflated_layout.findViewById(R.id.textViewFax)).setText(contatto.getFax());
                        ((TextView)inflated_layout.findViewById(R.id.textViewEmail)).setText(contatto.getEmail());
    
    
    
                        RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    
                        if (recent == 0)
                        {
                            relativeParams.addRule(RelativeLayout.BELOW, R.id.headerListViewContatti);
                        }
                        else
                        {
                            relativeParams.addRule(RelativeLayout.BELOW, recent);
                        }
                        recent = inflated_layout.getId();
    
                        inflated_layout.setLayoutParams(relativeParams);
                        //inflated_layout.setLayoutParams( new RelativeLayout.LayoutParams(source));
    
                        parent.addView(inflated_layout);
                    }
    

    relativeLayout保留在ScrollView中,因此所有内容都可以滚动:)

        19
  •  1
  •   Community Mohan Dere    8 年前

    下面是对 @djunod answer

    public static void setListViewHeightBasedOnChildren(ListView listView)
    {
        ListAdapter listAdapter = listView.getAdapter();
        if(listAdapter == null) return;
        if(listAdapter.getCount() <= 1) return;
    
        int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
        int totalHeight = 0;
        View view = null;
        for(int i = 0; i < listAdapter.getCount(); i++)
        {
            view = listAdapter.getView(i, view, listView);
            view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }
    
        20
  •  1
  •   Community Mohan Dere    8 年前

    试试这个,这个对我有用,我忘了在哪里找到的,在堆栈溢出的某个地方, 我不是来解释为什么它不起作用的,但答案是:)。

        final ListView AturIsiPulsaDataIsiPulsa = (ListView) findViewById(R.id.listAturIsiPulsaDataIsiPulsa);
        AturIsiPulsaDataIsiPulsa.setOnTouchListener(new ListView.OnTouchListener() 
        {
            @Override
            public boolean onTouch(View v, MotionEvent event) 
            {
                int action = event.getAction();
                switch (action) 
                {
                    case MotionEvent.ACTION_DOWN:
                    // Disallow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(true);
                    break;
    
                    case MotionEvent.ACTION_UP:
                    // Allow ScrollView to intercept touch events.
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    break;
                }
    
                // Handle ListView touch events.
                v.onTouchEvent(event);
                return true;
            }
        });
        AturIsiPulsaDataIsiPulsa.setClickable(true);
        AturIsiPulsaDataIsiPulsa.setAdapter(AturIsiPulsaDataIsiPulsaAdapter);
    

    编辑!,我终于找到了密码。在这里!: ListView inside ScrollView is not scrolling on Android

        21
  •  1
  •   Alécio Carvalho Kingfisher Phuoc    11 年前

    尽管 setListViewHeightBasedOnChildren() 简单的 的版本 列表视图 为了重用任何适配器代码,这里是ListView的替代方案:

    import android.content.Context;
    import android.database.DataSetObserver;
    import android.util.AttributeSet;
    import android.util.Log;
    import android.view.View;
    import android.widget.LinearLayout;
    import android.widget.ListAdapter;
    
    public class StretchedListView extends LinearLayout {
    
    private final DataSetObserver dataSetObserver;
    private ListAdapter adapter;
    private OnItemClickListener onItemClickListener;
    
    public StretchedListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(LinearLayout.VERTICAL);
        this.dataSetObserver = new DataSetObserver() {
            @Override
            public void onChanged() {
                syncDataFromAdapter();
                super.onChanged();
            }
    
            @Override
            public void onInvalidated() {
                syncDataFromAdapter();
                super.onInvalidated();
            }
        };
    }
    
    public void setAdapter(ListAdapter adapter) {
        ensureDataSetObserverIsUnregistered();
    
        this.adapter = adapter;
        if (this.adapter != null) {
            this.adapter.registerDataSetObserver(dataSetObserver);
        }
        syncDataFromAdapter();
    }
    
    protected void ensureDataSetObserverIsUnregistered() {
        if (this.adapter != null) {
            this.adapter.unregisterDataSetObserver(dataSetObserver);
        }
    }
    
    public Object getItemAtPosition(int position) {
        return adapter != null ? adapter.getItem(position) : null;
    }
    
    public void setSelection(int i) {
        getChildAt(i).setSelected(true);
    }
    
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
    
    public ListAdapter getAdapter() {
        return adapter;
    }
    
    public int getCount() {
        return adapter != null ? adapter.getCount() : 0;
    }
    
    private void syncDataFromAdapter() {
        removeAllViews();
        if (adapter != null) {
            int count = adapter.getCount();
            for (int i = 0; i < count; i++) {
                View view = adapter.getView(i, null, this);
                boolean enabled = adapter.isEnabled(i);
                if (enabled) {
                    final int position = i;
                    final long id = adapter.getItemId(position);
                    view.setOnClickListener(new View.OnClickListener() {
    
                        @Override
                        public void onClick(View v) {
                            if (onItemClickListener != null) {
                                onItemClickListener.onItemClick(null, v, position, id);
                            }
                        }
                    });
                }
                addView(view);
    
            }
        }
    }
    }
    
        22
  •  1
  •   TacoEater    9 年前

    如果你想把一个列表视图放到一个滚动视图中,你应该重新考虑你的设计。您正在尝试将ScrollView放入ScrollView。干扰列表会影响列表性能。它是由Android设计成这样的。

    如果确实希望列表与其他元素位于同一个滚动条中,则只需在适配器中使用一个简单的switch语句将其他项添加到列表的顶部:

    class MyAdapter extends ArrayAdapter{
    
        public MyAdapter(Context context, int resource, List objects) {
            super(context, resource, objects);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
             ViewItem viewType = getItem(position);
    
            switch(viewType.type){
                case TEXTVIEW:
                    convertView = layouteInflater.inflate(R.layout.textView1, parent, false);
    
                    break;
                case LISTITEM:
                    convertView = layouteInflater.inflate(R.layout.listItem, parent, false);
    
                    break;            }
    
    
            return convertView;
        }
    
    
    }
    

        23
  •  0
  •   majinnaibu    13 年前

    如果LinearLayout有一个setAdapter方法,整个问题就会消失,因为当你告诉别人使用它时,另一种方法将是微不足道的。

    您需要创建一个自定义适配器来组合要滚动的所有内容,并将ListView的适配器设置为该适配器。

    我手头没有样本代码,但如果你想要这样的东西。

    <ListView/>
    
    (other content)
    
    <ListView/>
    

    然后需要创建一个表示所有内容的适配器。ListView/适配器足够聪明,可以处理不同的类型,但是您需要自己编写适配器。

        24
  •  0
  •   Durgadass S    11 年前

    当我们放置 ListView ScrollView 出现了两个问题。一个是 以未指定的模式测量其子级,因此 列表视图 卷轴视图 列表视图

    但是我们 可以 地方 列表视图 里面 有一些解决办法。 This post ,解释了解决方法。通过这种变通方法,我们还可以保留 列表视图

        25
  •  0
  •   Saksham    9 年前

    不要将listview放在Scrollview中,而是将listview和Scrollview打开之间的其余内容作为单独的视图,并将该视图设置为listview的标题。所以你最终只能用列表视图来控制滚动。

        26
  •  0
  •   Garg    8 年前
        27
  •  0
  •   Zohab Ali    4 年前

    listview 里面 scrollview . 相反,你应该使用 NestedScrollView 作为家长和回收者查看里面。。。。因为它处理很多滚动问题

        28
  •  -1
  •   myforums    11 年前

    下面是我的代码版本,用于计算列表视图的总高度。这个对我有用:

       public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null || listAdapter.getCount() < 2) {
            // pre-condition
            return;
        }
    
        int totalHeight = 0;
        int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(BCTDApp.getDisplaySize().width, View.MeasureSpec.AT_MOST);
        int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            if (listItem instanceof ViewGroup) listItem.setLayoutParams(lp);
            listItem.measure(widthMeasureSpec, heightMeasureSpec);
            totalHeight += listItem.getMeasuredHeight();
        }
    
        totalHeight += listView.getPaddingTop() + listView.getPaddingBottom();
        totalHeight += (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight;
        listView.setLayoutParams(params);
        listView.requestLayout();
    }