Android嵌套滑动控件的冲突解决和ViewPager适配当前子控件高度不留空白的办法

来源:互联网 发布:九州通网络销售平台 编辑:程序博客网 时间:2024/05/21 06:12

最近项目有一个需求,需要多层可滑动控件的嵌套展示,demo效果如下,demo的下载地址在最后



咋一看好像挺简单啊,不就是一个ScrollView + ViewPager + ListView吗,我开始也这样觉得,也用的这种方式实现,结果始终和效果不对劲。这里总结几点问题:

  • 两个或两个以上的滑动控件嵌套时,如果layout_height采用的是wrap_content会造成内部滑动控件的高度不能正确的计算,会导致内部滑动控件的高度始终为0,除非你用定值设置,比如300dp。
  • 两个相同滑动方向的滑动控件嵌套,会使其中一个控件的滑动事件失效。
  • 如果采用ScrollView作为最外层的滑动控件,则会产生莫名其妙的移位BUG,通过日志发现是scrollY的异常变化,但是通过scrollTo方法是无效的。
  • ViewPager嵌套ListView的时候,默认ViewPager的高度是所有ListView中最高的那个,因此会造成其他ListView底部会有一大片的补白。

上面是我总结的发生过的几个问题,也许你的问题就是上面中的几个,也许还有些问题没有总结到,不过我相信此篇博客一样会对你有帮助。
好了,我们首先列出来我们需要解决的几件事情。
  • 刚才说了,使用ScrollView作为最外层滑动控件来嵌套其他滑动控件,会有莫名其妙的位移BUG,因此应该换一种滑动控件作为最外层的容器。
  • 两个滑动控件嵌套,内部滑动控件的高度默认会是0,除非你用定值设置,如果不想用定值设置,那么就需要自定义这个滑动控件,手动的计算该滑动控件。
  • ViewPager嵌套ListView会有数据少的ListView底部出现一大片的空白,因此这里我们也需要自定义ViewPager来动态计算当前的ListView的高度。
  • ListView作为顶层滑动控件的子滑动控件ViewPager的子滑动控件,高度默认当然也是0,这里我们也需要进行自定义ListView计算高度。

首先我们解决第一个问题,也就是拿什么控件来代替ScrollView作为顶层滑动控件。答案是ListView,有的小伙伴儿就不明白了,ListView作为顶层控件?不会吧这要怎么弄?说实话我当初采用ListView只考虑到一个原因:ListView不会有位移的BUG。接下来我用一张图来讲解。

由图中可以看到,顶层的ListView包含了两个部分,一个是Header,包括一些其他的控件以及IndicatorView导航条,然后就是ListView的Item了,重点是这个Item的数量只有一个,也就是拿ViewPager作为Item。然后ViewPager里面嵌套了Fragment作为碎片的展示,每一个Fragment又包含了一个ListView作为数据列表的展示。下面给出最顶层的滑动控件的代码:
首先是Activity的布局文件:
actvity_main.xml
<?xml version="1.0" encoding="utf-8"?><ListView xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/listView"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:cacheColorHint="@android:color/transparent"    android:divider="@null"    android:dividerHeight="0dp"    android:listSelector="@android:color/transparent" />

很简单,就只是一个ListView。然后是MainActiivity.class:
public class MainActivity extends FragmentActivity {    private TabPageIndicator indicator;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ListView listView = (ListView) findViewById(R.id.listView);        View header = View.inflate(this, R.layout.header, null);        indicator = (TabPageIndicator) header.findViewById(R.id.indicator);        listView.addHeaderView(header);        listView.setAdapter(new CustomAdapter(this));    }    public class CustomAdapter extends BaseAdapter{        private View view;        private WrapContentViewPager viewPager;        public CustomAdapter(Context context) {            view = View.inflate(context, R.layout.item_main, null);            viewPager = (WrapContentViewPager) view.findViewById(R.id.viewPager);            viewPager.setAdapter(new ListFragmentAdapter(viewPager, getSupportFragmentManager()));            indicator.setViewPager(viewPager);            viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {                @Override                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {                }                @Override                public void onPageSelected(int position) {                    viewPager.resetHeight(position);                    indicator.setCurrentItem(position);                }                @Override                public void onPageScrollStateChanged(int state) {                }            });            viewPager.resetHeight(0);        }        @Override        public int getCount() {            return 1;        }        @Override        public Object getItem(int position) {            return null;        }        @Override        public long getItemId(int position) {            return 0;        }        @Override        public View getView(int position, View convertView, ViewGroup parent) {            return view;        }    }}

在MainActivity主要做了两件事:
1、引入了单独的layout文件作为ListView的header
2、从header中实例化了ViewPager的导航控件Indicator
3、设置ListView的自定义Adapter,使getCount返回1,只显示一个Item
4、在唯一的Item中实例化了自定义的ViewPager,并设置了适配器Adapter

首先是header的布局文件:header.xml
<?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="wrap_content"    android:orientation="vertical"    >    <TextView        android:layout_width="match_parent"        android:layout_height="80dp"        android:gravity="center"        android:background="@android:color/holo_red_light"        android:text="Hello World!" />    <TextView        android:layout_width="match_parent"        android:layout_height="80dp"        android:gravity="center"        android:background="@android:color/holo_blue_light"        android:text="Hello World!" />    <TextView        android:layout_width="match_parent"        android:layout_height="80dp"        android:gravity="center"        android:background="@android:color/holo_orange_light"        android:text="Hello World!" />    <TextView        android:layout_width="match_parent"        android:layout_height="80dp"        android:gravity="center"        android:background="@android:color/holo_green_light"        android:text="Hello World!" />    <cc.wxf.androiddemo.indicator.TabPageIndicator        android:id="@+id/indicator"        android:layout_width="match_parent"        android:layout_height="wrap_content"/></LinearLayout>
这儿的header只包含了一些TextView作为demo展示,然后包含了导航控件Indicator。接着是ListView唯一一项Item的布局文件item_main.xml:
<?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="wrap_content">    <cc.wxf.androiddemo.WrapContentViewPager        android:id="@+id/viewPager"        android:layout_width="match_parent"        android:layout_height="wrap_content"/></LinearLayout>

第一层控件的展示就结束了,关键是第二层的展示问题,ViewPager + Fragment + ListView。
上面已经说了,ViewPager作为可滑动的控件,嵌套在ListView里面,如果不做特殊的操作,那么高度就一直为0,那么需要怎样来自定义呢?
我们理出来这个ViewPager需要做到哪些事情:
  • 需要知道所有子控件的高度
  • 需要重写onMeasure方法,使当前显示的子控件的高度为ViewPager的高度
  • 需要在page发生改变的时候,动态改变ViewPager的高度为当前子控件的高度
首先给出自定义ViewPager的源代码:WrapContentViewPager.class
package cc.wxf.androiddemo;import android.content.Context;import android.support.v4.view.ViewPager;import android.util.AttributeSet;import android.widget.LinearLayout;import java.util.HashMap;import java.util.Map;public class WrapContentViewPager extends ViewPager {    private Map<Integer, Integer> maps = new HashMap<Integer, Integer>();    private int current;    public WrapContentViewPager(Context context, AttributeSet attrs) {        super(context, attrs);    }    public WrapContentViewPager(Context context) {        super(context);    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int height = 0;        if(maps.size() > current){            height = maps.get(current + 1);        }        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);        super.onMeasure(widthMeasureSpec, heightMeasureSpec);    }    public void resetHeight(int current){        this.current = current;        if(maps.size() > current){            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();            if(layoutParams == null){                layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, maps.get(current + 1));            }else{                layoutParams.height = maps.get(current + 1);            }            setLayoutParams(layoutParams);        }    }    public void calculate(int type, int height){        maps.put(type, height);    }}

原理很简单,首先给出了一个Map的数据结构,保存了所有的子控件的位置以及对应的高度的映射表,然后给了一个current字段,表示当前显示的页面的索引。在onMeasure方法中,动态的根据当前的显示索引计算出当前子控件的高度,然后赋值给ViewPager。在resetHeight方法中,改变当前子控件的索引,并动态得改变当前ViewPager的高度。在calculate方法中,将子控件对应的位置和高度放入映射表,calculate方法是在自定义ListView中调用的,原因在文章后面就会明白了。
然后是ViewPager对应的FragmentPageAdapter的代码:
package cc.wxf.androiddemo;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentPagerAdapter;import java.util.ArrayList;import java.util.List;import cc.wxf.androiddemo.indicator.IconPagerAdapter;/** * Created by ccwxf on 2016/6/17. */public class ListFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter{    private List<ListFragment> fragments = new ArrayList<ListFragment>();    private static final String[] CONTENT = new String[] { "Calendar", "Camera", "Alarms", "Location" };    public ListFragmentAdapter(WrapContentViewPager viewPager, FragmentManager fm) {        super(fm);        fragments.add(new ListFragment(viewPager ,1));        fragments.add(new ListFragment(viewPager, 2));        fragments.add(new ListFragment(viewPager, 3));    }    @Override    public Fragment getItem(int position) {        return fragments.get(position);    }    @Override    public int getIconResId(int index) {        return R.drawable.selector_indicator;    }    @Override    public CharSequence getPageTitle(int position) {        return CONTENT[position % CONTENT.length].toUpperCase();    }    @Override    public int getCount() {        return fragments.size();    }}

这里的Adapter实现了IconPagerAdapter接口只是为了兼容导航控件Indicator的使用,对于导航控件Indicator的使用,请参考Github的开源库:ViewPagerIndicator
然后是ListFragment的代码:
package cc.wxf.androiddemo;import android.annotation.SuppressLint;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import java.util.ArrayList;import java.util.List;/** * Created by ccwxf on 2016/6/17. */public class ListFragment extends Fragment {    private WrapContentViewPager viewPager;    private int type;    public ListFragment() {    }    @SuppressLint("ValidFragment")    public ListFragment(WrapContentViewPager viewPager, int type) {        this.viewPager = viewPager;        this.type = type;    }    @Override    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.fragment_item, null);        WrapContentListView listView = (WrapContentListView) view.findViewById(R.id.listView);        List<String> data = new ArrayList<String>();        for(int i = 0; i < type * 5; i++){            data.add("aaa");        }        listView.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, data));        viewPager.calculate(type, listView.getRealHeight());        return view;    }}

这里的ListFragment只是做了一个自定义ListView的一个初始化。大家要特别注意的是在onCreateView方法中的viewPager.calculate方法,这里将对应子控件ListView的高度传回了ViewPager,并且这句代码必须在setAdapter之后执行,要问为什么?别急,咱还有一个fragment_item.xml的布局文件没有公布,其实超级简单。。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="match_parent"    android:layout_height="match_parent">    <cc.wxf.androiddemo.WrapContentListView        android:id="@+id/listView"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:cacheColorHint="@android:color/transparent"        android:divider="@android:color/darker_gray"        android:dividerHeight="@dimen/divider"        android:listSelector="@android:color/transparent" /></LinearLayout>

是不是超级简单。。其实就包含了一个自定义的ListView,那么最主要的工作来了,这个自定义的ListView该怎么写。
package cc.wxf.androiddemo;import android.content.Context;import android.util.AttributeSet;import android.view.View;import android.widget.ListAdapter;import android.widget.ListView;/** * Created by ccwxf on 2016/6/17. */public class WrapContentListView extends ListView {    private int height;    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 setAdapter(ListAdapter adapter) {        super.setAdapter(adapter);        View item = adapter.getView(0, null, null);        item.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));        int itemHeight = item.getMeasuredHeight();        int count = adapter.getCount();        height = itemHeight * count + getResources().getDimensionPixelSize(R.dimen.divider) * count;        measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), height);    }    public int getRealHeight(){        return height;    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));    }}

在setAdapter之后,动态的measure了第一条Item的高度,并且累加了count数量个item的高度和divider的高度(别小看这个divider的高度,如果不加上会导致最后一个Item无法显示),这里也就出现了一个限制:最内层的ListView的每一个Item的高度必须是一致的,也就是说Item的样式只能相同。否则就没办法计算,有的小伙伴儿会问了,那我为什么不把每一个Item都measure一下呢,你仔细想想如果有count为100呢?
然后是getRealHeight方法,是将计算出来的height返回出去,现在大家知道了为什么这个方法必须在setAdapter方法之后调用了吧。在onMeasure方法中,直接将计算出来的height设置我高度。这里又有好问的小伙伴儿要发问了:这儿的height会不会等于0啊?提这个问题的小伙伴最好想一想setAdapter和onMeasure的调用顺序,在本文中也就是onCreateView和onMeasure的调用顺序,聪明的小伙伴儿被我这么一点醒,是不是立刻就明白啦?

最后给出Demo的下载地址:
点我下载Demo


3 0
原创粉丝点击