Android -- 自定义实现横竖双向滚动的列表(ListView)布局

2,023 阅读24分钟

  1.   
    终于忙完手头上的工作了,难得有时间再唠叨一篇博客。在刚刚处理完的项目需求中,有一个小需求是客户要求查询出的所有数据一屏显示,如果显示不全,要做成可以左右滑动查看的形式(PS:原来的布局仅仅是一个ListView,然后显示几个重要数据,类似于数据表格)。既然客户要求了,那咱作为程序猿的就得赶紧实现啊(相信很多程序猿小伙伴都有这种经历,需求一遍一遍的提,一遍一遍的改,今天这个样,明天那个样,心里每天都有上百万匹什么马奔腾而过(最近老是能看到工作猝死的新闻,还好我心里承受能力还可以,要不然一天上百万匹马冲击我的小心脏,我还不得… 惊恐),但是没办法呀,谁让人家是客户涅……)好了,不说废话了,不就是需求吗,你提我改就是喽鄙视

    首先先让我们看一下最终实现的效果图,用的模拟器演示,有点卡顿,真机不会这样。(样子有点丑,不过很好用哦)

     

好了,效果就是上面的那个样子,接下来让我们看看如何用代码实现,这里只贴主要代码,文章最后提供源码下载。

一、分析

要实现上面的效果其实很简单,此表格分为两部分,最上面一行为标题头,下面为数据列表,看图,没有什么是一张图解决不了的问题,实在不行,再加一滴风油精安静

二、代码实现

1、首先列表的上下滚动还是使用ListView,这没什么好说的,代码就不贴了;
2、横向滚动 自定义CustomHScrollView类,继承HorizontalScrollView;
  1. public class CustomHScrollView extends HorizontalScrollView {  
  2.   
  3.     ScrollViewObserver mScrollViewObserver = new ScrollViewObserver();  
  4.   
  5.     public CustomHScrollView(Context context) {  
  6.         super(context);  
  7.     }  
  8.   
  9.     public CustomHScrollView(Context context, AttributeSet attrs) {  
  10.         super(context, attrs);  
  11.     }  
  12.   
  13.     public CustomHScrollView(Context context, AttributeSet attrs, int defStyleAttr) {  
  14.         super(context, attrs, defStyleAttr);  
  15.     }  
  16.   
  17.     @Override  
  18.     public boolean onTouchEvent(MotionEvent ev) {  
  19.         return super.onTouchEvent(ev);  
  20.     }  
  21.   
  22.     @Override  
  23.     protected void onScrollChanged(int l,  int t, int oldl, int oldt) {  
  24.         //滚动时通知观察者  
  25.         if (mScrollViewObserver != null) {  
  26.             mScrollViewObserver.NotifyOnScrollChanged(l, t, oldl, oldt);  
  27.         }  
  28.         super.onScrollChanged(l, t, oldl, oldt);  
  29.     }  
  30.   
  31.     /* 
  32.      * 当发生了滚动事件时接口,供外部访问 
  33.      */  
  34.     public static interface OnScrollChangedListener {  
  35.         public void onScrollChanged(int l,  int t, int oldl, int oldt);  
  36.     }  
  37.   
  38.     /* 
  39.      * 添加滚动事件监听 
  40.      * */  
  41.     public void AddOnScrollChangedListener(OnScrollChangedListener listener) {  
  42.         mScrollViewObserver.AddOnScrollChangedListener(listener);  
  43.     }  
  44.   
  45.     /* 
  46.      * 移除滚动事件监听 
  47.      * */  
  48.     public void RemoveOnScrollChangedListener(OnScrollChangedListener listener) {  
  49.         mScrollViewObserver.RemoveOnScrollChangedListener(listener);  
  50.     }  
  51.     /* 
  52.      * 滚动观察者 
  53.      */  
  54.     public static class ScrollViewObserver {  
  55.         List<OnScrollChangedListener> mChangedListeners;  
  56.   
  57.         public ScrollViewObserver() {  
  58.             super();  
  59.             mChangedListeners = new ArrayList<OnScrollChangedListener>();  
  60.         }  
  61.         //添加滚动事件监听  
  62.         public void AddOnScrollChangedListener(OnScrollChangedListener listener) {  
  63.             mChangedListeners.add(listener);  
  64.         }  
  65.         //移除滚动事件监听  
  66.         public void RemoveOnScrollChangedListener(OnScrollChangedListener listener) {  
  67.             mChangedListeners.remove(listener);  
  68.         }  
  69.         //通知  
  70.         public void NotifyOnScrollChanged(int l,  int t, int oldl, int oldt) {  
  71.             if (mChangedListeners == null || mChangedListeners.size() ==  0) {  
  72.                 return;  
  73.             }  
  74.             for (int i = 0; i < mChangedListeners.size(); i++) {  
  75.                 if (mChangedListeners.get(i) != null) {  
  76.                     mChangedListeners.get(i).onScrollChanged(l, t, oldl, oldt);  
  77.                 }  
  78.             }  
  79.         }  
  80.     }  
  81. }  
public class CustomHScrollView extends HorizontalScrollView {

    ScrollViewObserver mScrollViewObserver = new ScrollViewObserver();

    public CustomHScrollView(Context context) {
        super(context);
    }

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

    public CustomHScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return super.onTouchEvent(ev);
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        //滚动时通知观察者
        if (mScrollViewObserver != null) {
            mScrollViewObserver.NotifyOnScrollChanged(l, t, oldl, oldt);
        }
        super.onScrollChanged(l, t, oldl, oldt);
    }

    /*
     * 当发生了滚动事件时接口,供外部访问
     */
    public static interface OnScrollChangedListener {
        public void onScrollChanged(int l, int t, int oldl, int oldt);
    }

    /*
     * 添加滚动事件监听
     * */
    public void AddOnScrollChangedListener(OnScrollChangedListener listener) {
        mScrollViewObserver.AddOnScrollChangedListener(listener);
    }

    /*
     * 移除滚动事件监听
     * */
    public void RemoveOnScrollChangedListener(OnScrollChangedListener listener) {
        mScrollViewObserver.RemoveOnScrollChangedListener(listener);
    }
    /*
     * 滚动观察者
     */
    public static class ScrollViewObserver {
        List<OnScrollChangedListener> mChangedListeners;

        public ScrollViewObserver() {
            super();
            mChangedListeners = new ArrayList<OnScrollChangedListener>();
        }
        //添加滚动事件监听
        public void AddOnScrollChangedListener(OnScrollChangedListener listener) {
            mChangedListeners.add(listener);
        }
        //移除滚动事件监听
        public void RemoveOnScrollChangedListener(OnScrollChangedListener listener) {
            mChangedListeners.remove(listener);
        }
        //通知
        public void NotifyOnScrollChanged(int l, int t, int oldl, int oldt) {
            if (mChangedListeners == null || mChangedListeners.size() == 0) {
                return;
            }
            for (int i = 0; i < mChangedListeners.size(); i++) {
                if (mChangedListeners.get(i) != null) {
                    mChangedListeners.get(i).onScrollChanged(l, t, oldl, oldt);
                }
            }
        }
    }
}

实现图中的效果最重要的是如何让数据行与标题行保持同时同向滑动,由上面的代码可以看出,我定义了一个滚动观察者,用于监听滚动事件,每次滚动事件的触发(包括标题头和数据行每一行的滚动)都会通知给观察者,之后观察者再通知给它的订阅者,保持滚动的一致性。代码中都有注释,一目了然。

3、出此之外还要自定义一个拦截onTouch事件的布局
  1. public class InterceptScrollLinearLayout extends LinearLayout {  
  2.   
  3.     public InterceptScrollLinearLayout(Context context) {  
  4.         super(context);  
  5.     }  
  6.   
  7.     public InterceptScrollLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {  
  8.         super(context, attrs, defStyleAttr);  
  9.     }  
  10.   
  11.     public InterceptScrollLinearLayout(Context context, AttributeSet attrs) {  
  12.         super(context, attrs);  
  13.     }  
  14.   
  15.     @Override  
  16.     public boolean onInterceptTouchEvent(MotionEvent ev) {  
  17.         return true;  
  18.     }  
  19. }  
public class InterceptScrollLinearLayout extends LinearLayout {

    public InterceptScrollLinearLayout(Context context) {
        super(context);
    }

    public InterceptScrollLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return true;
    }
}

关键代码就是上面这两个自定义类

来看MainActivity,只贴部分关键代码
  1. public class MainActivity extends AppCompatActivity {  
  2.   
  3.     private RelativeLayout mHead;//标题头  
  4.     private ListView mListView;  
  5.     private List<TestData> mDataList;  
  6.     private ListViewAdapter mAdapter;  
  7.     CustomHScrollView mScrollView;  
  8.   
  9.     @Override  
  10.     protected void onCreate(Bundle savedInstanceState) {  
  11.         super.onCreate(savedInstanceState);  
  12.         setContentView(R.layout.activity_main);  
  13.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);  
  14.         setSupportActionBar(toolbar);  
  15.         initView();  
  16.         initData();  
  17.     }  
  18.   
  19.     private void initView(){  
  20.         mListView = (ListView) findViewById(R.id.list_view);  
  21.         mScrollView = (CustomHScrollView) findViewById(R.id.h_scrollView);  
  22.         mHead = (RelativeLayout) findViewById(R.id.head_layout);  
  23.         mHead.setBackgroundResource(R.color.colorAccent);  
  24.         mHead.setFocusable(true);  
  25.         mHead.setClickable(true);  
  26.         mHead.setOnTouchListener(new MyTouchLinstener());  
  27.         mListView.setOnTouchListener(new MyTouchLinstener());  
  28.     }  
  29.   
  30.     /** 
  31.      * 加载数据 
  32.      */  
  33.     private void initData(){  
  34.         mDataList = new ArrayList<>();  
  35.         TestData data = null;  
  36.         for (int i = 1; i <=  100; i++) {  
  37.             data = new TestData();  
  38.             data.setText1("第"+i+"行-1");  
  39.             data.setText2("第"+i+"行-2");  
  40.             data.setText3("第"+i+"行-3");  
  41.             data.setText4("第"+i+"行-4");  
  42.             data.setText5("第"+i+"行-5");  
  43.             data.setText6("第"+i+"行-6");  
  44.             data.setText7("第"+i+"行-7");  
  45.             mDataList.add(data);  
  46.         }  
  47.         setData();  
  48.     }  
  49.   
  50.     private void setData(){  
  51.         mAdapter = new ListViewAdapter(this, mDataList, mHead);  
  52.         mListView.setAdapter(mAdapter);  
  53.     }  
  54.   
  55.     class MyTouchLinstener implements View.OnTouchListener {  
  56.   
  57.         @Override  
  58.         public boolean onTouch(View arg0, MotionEvent arg1) {  
  59.             //当在表头和listView控件上touch时,将事件分发给 ScrollView  
  60.             HorizontalScrollView headSrcrollView = (HorizontalScrollView) mHead.findViewById(R.id.h_scrollView);  
  61.             headSrcrollView.onTouchEvent(arg1);  
  62.             return false;  
  63.         }  
  64.     }  
  65.   
  66.     //...............  
  67. }  
public class MainActivity extends AppCompatActivity {

    private RelativeLayout mHead;//标题头
    private ListView mListView;
    private List<TestData> mDataList;
    private ListViewAdapter mAdapter;
    CustomHScrollView mScrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        initView();
        initData();
    }

    private void initView(){
        mListView = (ListView) findViewById(R.id.list_view);
        mScrollView = (CustomHScrollView) findViewById(R.id.h_scrollView);
        mHead = (RelativeLayout) findViewById(R.id.head_layout);
        mHead.setBackgroundResource(R.color.colorAccent);
        mHead.setFocusable(true);
        mHead.setClickable(true);
        mHead.setOnTouchListener(new MyTouchLinstener());
        mListView.setOnTouchListener(new MyTouchLinstener());
    }

    /**
     * 加载数据
     */
    private void initData(){
        mDataList = new ArrayList<>();
        TestData data = null;
        for (int i = 1; i <= 100; i++) {
            data = new TestData();
            data.setText1("第"+i+"行-1");
            data.setText2("第"+i+"行-2");
            data.setText3("第"+i+"行-3");
            data.setText4("第"+i+"行-4");
            data.setText5("第"+i+"行-5");
            data.setText6("第"+i+"行-6");
            data.setText7("第"+i+"行-7");
            mDataList.add(data);
        }
        setData();
    }

    private void setData(){
        mAdapter = new ListViewAdapter(this, mDataList, mHead);
        mListView.setAdapter(mAdapter);
    }

    class MyTouchLinstener implements View.OnTouchListener {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            //当在表头和listView控件上touch时,将事件分发给 ScrollView
            HorizontalScrollView headSrcrollView = (HorizontalScrollView) mHead.findViewById(R.id.h_scrollView);
            headSrcrollView.onTouchEvent(arg1);
            return false;
        }
    }

    //...............
}

再看适配器

  1. public class ListViewAdapter extends BaseAdapter {  
  2.   
  3.     private Context mContext;  
  4.     private List<TestData> mList;  
  5.     private LayoutInflater mInflater;  
  6.     private RelativeLayout mHead;  
  7.   
  8.     public ListViewAdapter(Context context, List<TestData> list, RelativeLayout head) {  
  9.         this.mContext = context;  
  10.         this.mList = list;  
  11.         this.mHead = head;  
  12.         this.mInflater = LayoutInflater.from(context);  
  13.     }  
  14.   
  15.     @Override  
  16.     public int getCount() {  
  17.         return mList.size();  
  18.     }  
  19.   
  20.     @Override  
  21.     public Object getItem(int i) {  
  22.         return mList.get(i);  
  23.     }  
  24.   
  25.     @Override  
  26.     public long getItemId(int i) {  
  27.         return i;  
  28.     }  
  29.   
  30.     @Override  
  31.     public View getView(int i, View view, ViewGroup group) {  
  32.         MyViewHolder holder = null;  
  33.         if (view == null){  
  34.             view = mInflater.inflate(R.layout.list_item, group, false);  
  35.             holder = new MyViewHolder();  
  36.             CustomHScrollView scrollView = (CustomHScrollView) view.findViewById(R.id.h_scrollView);  
  37.             holder.scrollView = scrollView;  
  38.               
  39. //..........  
  40.   
  41.             CustomHScrollView headSrcrollView = (CustomHScrollView) mHead.findViewById(R.id.h_scrollView);  
  42.             //添加滚动监听事件  
  43.             headSrcrollView.AddOnScrollChangedListener(new OnScrollChangedListenerImp(scrollView));  
  44.   
  45.             view.setTag(holder);  
  46.         }else{  
  47.             holder = (MyViewHolder) view.getTag();  
  48.         }  
  49.   
  50.         //.........  
  51.   
  52.         return view;  
  53.     }  
  54.   
  55.     class OnScrollChangedListenerImp implements CustomHScrollView.OnScrollChangedListener {  
  56.         CustomHScrollView mScrollViewArg;  
  57.   
  58.         public OnScrollChangedListenerImp(CustomHScrollView scrollViewar) {  
  59.             mScrollViewArg = scrollViewar;  
  60.         }  
  61.   
  62.         @Override  
  63.         public void onScrollChanged(int l,  int t, int oldl, int oldt) {  
  64.             mScrollViewArg.smoothScrollTo(l, t);  
  65.              
  66.         }  
  67.     };  
  68.   
  69.     class MyViewHolder{  
  70.         //........  
  71.     }  
  72. }  
public class ListViewAdapter extends BaseAdapter {

    private Context mContext;
    private List<TestData> mList;
    private LayoutInflater mInflater;
    private RelativeLayout mHead;

    public ListViewAdapter(Context context, List<TestData> list, RelativeLayout head) {
        this.mContext = context;
        this.mList = list;
        this.mHead = head;
        this.mInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int i) {
        return mList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup group) {
        MyViewHolder holder = null;
        if (view == null){
            view = mInflater.inflate(R.layout.list_item, group, false);
            holder = new MyViewHolder();
            CustomHScrollView scrollView = (CustomHScrollView) view.findViewById(R.id.h_scrollView);
            holder.scrollView = scrollView;
            
//..........

            CustomHScrollView headSrcrollView = (CustomHScrollView) mHead.findViewById(R.id.h_scrollView);
            //添加滚动监听事件
            headSrcrollView.AddOnScrollChangedListener(new OnScrollChangedListenerImp(scrollView));

            view.setTag(holder);
        }else{
            holder = (MyViewHolder) view.getTag();
        }

        //.........

        return view;
    }

    class OnScrollChangedListenerImp implements CustomHScrollView.OnScrollChangedListener {
        CustomHScrollView mScrollViewArg;

        public OnScrollChangedListenerImp(CustomHScrollView scrollViewar) {
            mScrollViewArg = scrollViewar;
        }

        @Override
        public void onScrollChanged(int l, int t, int oldl, int oldt) {
            mScrollViewArg.smoothScrollTo(l, t);
           
        }
    };

    class MyViewHolder{
        //........
    }
}

对应的xml文件
  1. <?xml version="1.0"  encoding="utf-8"?>  
  2. <RelativeLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     xmlns:tools="http://schemas.android.com/tools"  
  6.     android:id="@+id/content_main"  
  7.     android:layout_width="match_parent"  
  8.     android:layout_height="match_parent"  
  9.     app:layout_behavior="@string/appbar_scrolling_view_behavior"  
  10.     tools:context="com.hbh.cl.listviewhorizontalscrolldemo.MainActivity"  
  11.     tools:showIn="@layout/activity_main">  
  12.   
  13.     <include  
  14.         android:id="@+id/head_layout"  
  15.         layout="@layout/list_item"  
  16.         />  
  17.   
  18.     <ListView  
  19.         android:id="@+id/list_view"  
  20.         android:layout_width="fill_parent"  
  21.         android:layout_height="fill_parent"  
  22.         android:layout_below="@+id/head_layout"  
  23.         android:cacheColorHint="@android:color/transparent"  
  24.         android:dividerHeight="1dp"  
  25.         android:divider="@color/gray">  
  26.     </ListView>  
  27. </RelativeLayout>  
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.hbh.cl.listviewhorizontalscrolldemo.MainActivity"
    tools:showIn="@layout/activity_main">

    <include
        android:id="@+id/head_layout"
        layout="@layout/list_item"
        />

    <ListView
        android:id="@+id/list_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/head_layout"
        android:cacheColorHint="@android:color/transparent"
        android:dividerHeight="1dp"
        android:divider="@color/gray">
    </ListView>
</RelativeLayout>
list_item.xml文件
  1. <?xml version="1.0"  encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.                 android:layout_width="match_parent"  
  4.                 android:layout_height="wrap_content"  
  5.                 android:background="@color/white"  
  6.                 android:descendantFocusability="blocksDescendants"  
  7.                 android:orientation="horizontal"  
  8.                 android:padding="5dp"  >  
  9.   
  10.     <TextView  
  11.         android:id="@+id/textView_1"  
  12.         android:layout_width="80dp"  
  13.         android:layout_height="40dp"  
  14.         android:layout_alignParentLeft="true"  
  15.         android:layout_marginLeft="2dp"  
  16.         android:layout_marginRight="2dp"  
  17.         android:gravity="center"  
  18.         android:textAppearance="?android:attr/textAppearanceMedium"  
  19.         android:maxLines="2"  
  20.         android:ellipsize="end"  
  21.         android:text="标题1"  
  22.         android:textColor="@color/black"  
  23.         android:textSize="14sp" />  
  24.   
  25.     <com.hbh.cl.listviewhorizontalscrolldemo.util.InterceptScrollLinearLayout  
  26.         android:id="@+id/scroollContainter"  
  27.         android:layout_width="fill_parent"  
  28.         android:layout_height="40dp"  
  29.         android:layout_alignParentRight="true"  
  30.         android:layout_toRightOf="@id/textView_1"  
  31.         android:focusable="false" >  
  32.   
  33.         <com.hbh.cl.listviewhorizontalscrolldemo.util.CustomHScrollView  
  34.             android:id="@+id/h_scrollView"  
  35.             android:layout_width="fill_parent"  
  36.             android:layout_height="40dp"  
  37.             android:focusable="false"  
  38.             android:scrollbars="none"  >  
  39.   
  40.             <LinearLayout  
  41.                 android:layout_width="match_parent"  
  42.                 android:layout_height="match_parent"  
  43.                 android:focusable="false"  
  44.                 android:orientation="horizontal"  >  
  45.   
  46.                 <LinearLayout  
  47.                     android:layout_width="80dp"  
  48.                     android:layout_height="match_parent"  
  49.                     android:gravity="center"  
  50.                     android:layout_gravity="center"  
  51.                     android:orientation="vertical"  >  
  52.   
  53.                     <TextView  
  54.                         android:id= "@+id/textView_2"  
  55.                         android:layout_width= "match_parent"  
  56.                         android:layout_height= "wrap_content"  
  57.                         android:layout_marginLeft= "2dp"  
  58.                         android:layout_marginRight= "2dp"  
  59.                         android:text= "标题2"  
  60.                         android:textColor= "@color/black"  
  61.                         android:gravity= "center"  
  62.                         android:textSize= "14sp"  
  63.                         android:textAppearance= "?android:attr/textAppearanceMedium" />  
  64.   
  65.                 </LinearLayout>  
  66.   
  67.                <!-- ....省略...... -->  
  68.                   
  69.             </LinearLayout>  
  70.         </com.hbh.cl.listviewhorizontalscrolldemo.util.CustomHScrollView>  
  71.     </com.hbh.cl.listviewhorizontalscrolldemo.util.InterceptScrollLinearLayout>  
  72.   
  73. </RelativeLayout>  
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/white"
                android:descendantFocusability="blocksDescendants"
                android:orientation="horizontal"
                android:padding="5dp" >

    <TextView
        android:id="@+id/textView_1"
        android:layout_width="80dp"
        android:layout_height="40dp"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:maxLines="2"
        android:ellipsize="end"
        android:text="标题1"
        android:textColor="@color/black"
        android:textSize="14sp" />

    <com.hbh.cl.listviewhorizontalscrolldemo.util.InterceptScrollLinearLayout
        android:id="@+id/scroollContainter"
        android:layout_width="fill_parent"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@id/textView_1"
        android:focusable="false" >

        <com.hbh.cl.listviewhorizontalscrolldemo.util.CustomHScrollView
            android:id="@+id/h_scrollView"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:focusable="false"
            android:scrollbars="none" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:focusable="false"
                android:orientation="horizontal" >

                <LinearLayout
                    android:layout_width="80dp"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:layout_gravity="center"
                    android:orientation="vertical" >

                    <TextView
                        android:id="@+id/textView_2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="2dp"
                        android:layout_marginRight="2dp"
                        android:text="标题2"
                        android:textColor="@color/black"
                        android:gravity="center"
                        android:textSize="14sp"
                        android:textAppearance="?android:attr/textAppearanceMedium" />

                </LinearLayout>

               <!-- ....省略...... -->
                
            </LinearLayout>
        </com.hbh.cl.listviewhorizontalscrolldemo.util.CustomHScrollView>
    </com.hbh.cl.listviewhorizontalscrolldemo.util.InterceptScrollLinearLayout>

</RelativeLayout>
好了,代码基本上都贴出来了,至于其他的测试数据的类就不贴了,来,现在让我们跑一下我们的代码:

           

OK,非常完美,一切都显得那么和谐。但这都只是写死的数据,正常情况下是要通过网络请求获取数据,然后通过适配器展示数据的,咱们刚才的这种情况只能算是简单的模拟了网络请求展示数据,那么好了,我现在要刷新数据,刷新当前页面的数据,ok,咱们再增加一个刷新按钮,点击刷新,更新数据。

我们在MainActivity中增加一段代码:
  1. @Override  
  2.     public boolean onOptionsItemSelected(MenuItem item) {  
  3.   
  4.         int id = item.getItemId();  
  5.         if (id == R.id.action_settings) {  
  6.             initData();//刷新,重新加载数据  
  7.             if (mAdapter != null){  
  8.                 mAdapter.notifyDataSetChanged();  
  9.             }  
  10.             return true;  
  11.         }  
  12.   
  13.         return super.onOptionsItemSelected(item);  
  14.     }  
@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            initData();//刷新,重新加载数据
            if (mAdapter != null){
                mAdapter.notifyDataSetChanged();
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

这里我们重新执行initData()方法,模拟网络请求进行刷新,然后调用Adapter的notifyDataSetChanged()方法来刷新每个item的内容,好了,现在再来跑一下程序:


我擦,这是什么鬼,点击刷新之后,标题头与数据行内容完全错乱了,怎么回事呢???这是因为在我们点击刷新之后,Adapter调用notifyDataSetChanged()方法将listview中的每个item都强制刷新,但标题头并不是listview的一部分,所以保持原来的状态,造成错乱的问题。
那怎么解决呢???很简单,就是在我们点击刷新的时候,让标题头(可滑动部分)回到初始状态。
什么意思呢??咱们看,当我们在不向左滑动的情况下,刷新是不会出现任何问题的,当我们向左滑动之后,再刷新,出现了数据错乱的问题,那么好了,能不能在我们刷新的时候让标题头回到初始位置呢??当然可以,看代码

找到我们的ListViewAdapter,其中有这么几行代码:
  1. @Override  
  2.         public void onScrollChanged(int l,  int t, int oldl, int oldt) {  
  3.             mScrollViewArg.smoothScrollTo(l, t);  
  4.             if (n == 1) {//记录滚动的起始位置,避免因刷新数据引起错乱  
  5.                 new MainActivity().setPosData(oldl, oldt);  
  6.             }  
  7.             n++;  
  8.         }  
@Override
        public void onScrollChanged(int l, int t, int oldl, int oldt) {
            mScrollViewArg.smoothScrollTo(l, t);
            if (n == 1) {//记录滚动的起始位置,避免因刷新数据引起错乱
                new MainActivity().setPosData(oldl, oldt);
            }
            n++;
        }
这个方法就是在我们左右滚动时所执行的,我们加了一个标记,记录下第一次滚动时的位置oldl和oldt
MainActivity中对应的改动:
  1. @Override  
  2.    public boolean onOptionsItemSelected(MenuItem item) {  
  3.   
  4.        int id = item.getItemId();  
  5.        if (id == R.id.action_settings) {  
  6.            initData();//刷新,重新加载数据  
  7.            mScrollView.smoothScrollTo(leftPos, topPos);//每次刷新数据都让CustomHScrollView回到初始位置,避免错乱  
  8.            if (mAdapter != null){  
  9.                mAdapter.notifyDataSetChanged();  
  10.            }  
  11.            return true;  
  12.        }  
  13.   
  14.        return super.onOptionsItemSelected(item);  
  15.    }  
  16.   
  17.    /** 
  18.     * 记录CustomHScrollView的初始位置 
  19.     * @param l 
  20.     * @param t 
  21.     */  
  22.    public void setPosData(int l, int t){  
  23.        this.leftPos = l;  
  24.        this.topPos = t;  
  25.    }  
 @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_settings) {
            initData();//刷新,重新加载数据
            mScrollView.smoothScrollTo(leftPos, topPos);//每次刷新数据都让CustomHScrollView回到初始位置,避免错乱
            if (mAdapter != null){
                mAdapter.notifyDataSetChanged();
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 记录CustomHScrollView的初始位置
     * @param l
     * @param t
     */
    public void setPosData(int l, int t){
        this.leftPos = l;
        this.topPos = t;
    }
我们看到,在刷新的方法中我们增加了一行代码,让CustomHScrollView回到初始位置,好了,我们现在再来运行一下程序:

         

OK,非常完美,一切又都是那么和谐,但是……已经没有问题了!!!
好了,啰啰嗦嗦那么多,可能让你也觉得不明不白,还不如直接看源码来的实在。那好,源码双手奉上 源码传送门
如果觉得还不错,顺手给个赞,star一下吧微笑


1
0

我的同类文章