@Override public boolean isBottom() { final int childCount = getChildCount(); if (childCount <= 0) return false; final int itemsCount = getCount(); final int firstPosition = getFirstVisiblePosition(); final int lastPosition = firstPosition + childCount; final int lastBottom = getChildAt(childCount - 1).getBottom(); return lastPosition >= itemsCount && lastBottom <= getHeight() - getListPaddingBottom(); }
@Override public boolean isTop() { if (getChildCount() <= 0) return false; final int firstTop = getChildAt(0).getTop(); return getFirstVisiblePosition() == 0 && firstTop >= getListPaddingTop(); }
@Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: downX = ev.getX(); downY = ev.getY(); //如果滑动到了最底部,就允许继续向上滑动加载下一页,否者不允许 getParent().requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_MOVE: float dx = ev.getX() - downX; float dy = ev.getY() - downY; boolean allowParentTouchEvent; if (Math.abs(dy) > Math.abs(dx)) { //垂直方向滑动 if (dy > 0) { //位于顶部时下拉,让父View消费事件 allowParentTouchEvent = isTop(); } else { //位于底部时上拉,让父View消费事件 allowParentTouchEvent = isBottom(); } } else { //水平方向滑动 allowParentTouchEvent = true; } getParent().requestDisallowInterceptTouchEvent(!allowParentTouchEvent); } return super.dispatchTouchEvent(ev); }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_listview, container, false); listview = (VerticalListView) rootView.findViewById(R.id.listView); TextView textView1 = new TextView(getActivity()); textView1.setText("header1"); textView1.setGravity(Gravity.CENTER); textView1.setTextColor(Color.WHITE); textView1.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300)); textView1.setBackgroundColor(Color.GRAY); TextView textView2 = new TextView(getActivity()); textView2.setText("header2"); textView2.setGravity(Gravity.CENTER); textView2.setTextColor(Color.WHITE); textView2.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300)); textView2.setBackgroundColor(Color.DKGRAY); TextView textView3 = new TextView(getActivity()); textView3.setText("footer1"); textView3.setGravity(Gravity.CENTER); textView3.setTextColor(Color.WHITE); textView3.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300)); textView3.setBackgroundColor(Color.GRAY); listview.addHeaderView(textView1); listview.addHeaderView(textView2); listview.addFooterView(textView3); listview.setAdapter(new MyAdapter()); return rootView; }