当SwipeRefreshLayout内嵌listview的时候,滑动listview的时会启动swipeRefreshLayout的下拉刷新。我使用的解决办法是设置listview的滑动监听,重写滑动监听器,通过判断listview的第一可视item的index来判断是否需要刷新,如果不需要就把swipeRefreshLayout设置成不可滑动,否则设置成可滑动。我的listview放在了fragment里面,所以我用了最笨的方法,在fragment的构造方法里把activity的swipeRefreshLayout对象传递给了fragment:MyManageFragmentmanageFragment = new MyManageFragment(swipeRefreshLayout);transation.add(R.id.activity_mydevice_container, manageFragment);transation.commit();然后在fragment的onCreateView里面设置其listview的滑动监听:listview.setOnScrollListener(new SwpipeListViewOnScrollListener(swipeRefreshLayout));然后重写滑动监听器,通过判断listview的第一个可视的item的位置来决定是下拉刷新还是下滑,判断到是下滑的时候,通过设置传入的swipeRefreshLayout对象使其不可用:swipeRefreshLayout.setEnabled(false);重写监听器:/** * 由于Listview与下拉刷新的Scroll事件冲突, 使用这个ScrollListener可以避免Listview滑动异常 */public class SwpipeListViewOnScrollListener implements AbsListView.OnScrollListener { PRivate SwipeRefreshLayout mSwipeView; private AbsListView.OnScrollListener mOnScrollListener; public SwpipeListViewOnScrollListener(SwipeRefreshLayout swipeView) { mSwipeView = swipeView; } public SwpipeListViewOnScrollListener(SwipeRefreshLayout swipeView, AbsListView.OnScrollListener onScrollListener) { mSwipeView = swipeView; mOnScrollListener = onScrollListener; } @Override public void onScrollStateChanged(AbsListView absListView, int i) { } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { View firstView = absListView.getChildAt(firstVisibleItem); // 当firstVisibleItem是第0位。如果firstView==null说明列表为空,需要刷新;或者top==0说明已经到达列表顶部, 也需要刷新 if (firstVisibleItem == 0 && (firstView == null || firstView.getTop() == 0)) { mSwipeView.setEnabled(true);//可刷新 } else { mSwipeView.setEnabled(false);//不能刷新,此时为滑动 } if (null != mOnScrollListener) { mOnScrollListener.onScroll(absListView, firstVisibleItem, visibleItemCount, totalItemCount); } }}PS: 一开始想在activity里获取到frgment里面的listview对象,在activity里设置listview的滑动监听器,但是没有成功,对于fragment和activity的交互,理解还不是很够。MyManageFragmentmanageFragment = new MyManageFragment();transation.add(R.id.activity_mydevice_container, manageFragment,"mymanage_fragment");transation.commit();getSupportFragmentManager().executePendingTransactions(); //1--------------MymanageFragment myManageFragment = (MymanageFragment) getSupportFragmentManager().findFragmentByTag("mymanage_fragment");if (myManageFragment != null) { ListView listView = (ListView) myManageFragment.getView().findViewById(R.id.listview_mymanage); listView.setOnScrollListener(new SwpipeListViewOnScrollListener(swipeRefreshLayout));} else { toast("myManageFragment is null");}其中 myManageFragment.getView()返回的是null,有待进一步解决
新闻热点
疑难解答