Android scrollview中巢狀listview實現listview的下拉重新整理上拉載入更多
阿新 • • 發佈:2019-01-09
我們都知道在Android中scrollview和listview都能滑動,如果scrollview巢狀listview會出現一些問題,比如listview不能正常顯示item...但是在一些專案中,一些頁面內容比較多,需要在外面放一個scrollview,裡面還會巢狀listview,而listview上面還有很多佈局。這時候就會出現一些問題。所以遇見這種情況我們要重新listview的onMeasure方法,
設為最大模式(MeasureSpec.AT_MOST)這個也就是父元件,能夠給出的最大的空間,當前元件的長或寬最大隻能為這麼大,當然也可以比這個小。意思是在scrollview中讓listview顯示所有的item。
如果這時候還要實現listview的的下拉重新整理上拉載入更多,那就會比較麻煩了,因為listview上面還有很多佈局,顯然這時候用傳統的listview的下拉重新整理上拉載入更多是不行的。那麼我們是否可以換一種思路來想,我們是否可以封裝一個可以下拉重新整理,上拉更多的scrollview,在scrollview的上拉重新整理下拉更多的監聽事件裡呼叫listview的下拉重新整理上拉載入更多的方法,然後更新一下listview的adapter。是不是這樣就可以實現scrollview中巢狀listview的下拉重新整理上拉載入更多了。public class MyListView extends ListView{ public MyListView(Context context, AttributeSet attrs) { super(context, attrs); } public MyListView(Context context) { super(context); } public MyListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec( Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
public class PullToRefreshLayout extends RelativeLayout { public static final String TAG = "PullToRefreshLayout"; // 初始狀態 public static final int INIT = 0; // 釋放重新整理 public static final int RELEASE_TO_REFRESH = 1; // 正在重新整理 public static final int REFRESHING = 2; // 釋放載入 public static final int RELEASE_TO_LOAD = 3; // 正在載入 public static final int LOADING = 4; // 操作完畢 public static final int DONE = 5; // 當前狀態 private int state = INIT; // 重新整理回撥介面 private OnRefreshListener mListener; // 重新整理成功 public static final int SUCCEED = 0; // 重新整理失敗 public static final int FAIL = 1; // 按下Y座標,上一個事件點Y座標 private float downY, lastY; // 下拉的距離。注意:pullDownY和pullUpY不可能同時不為0 public float pullDownY = 0; // 上拉的距離 private float pullUpY = 0; // 釋放重新整理的距離 private float refreshDist = 200; // 釋放載入的距離 private float loadmoreDist = 200; private MyTimer timer; // 回滾速度 public float MOVE_SPEED = 8; // 第一次執行佈局 private boolean isLayout = false; // 在重新整理過程中滑動操作 private boolean isTouch = false; // 手指滑動距離與下拉頭的滑動距離比,中間會隨正切函式變化 private float radio = 2; // 下拉箭頭的轉180°動畫 private RotateAnimation rotateAnimation; // 均勻旋轉動畫 private RotateAnimation refreshingAnimation; // 下拉頭 private View refreshView; // 下拉的箭頭 private View pullView; // 正在重新整理的圖示 private View refreshingView; // 重新整理結果圖示 private View refreshStateImageView; // 重新整理結果:成功或失敗 private TextView refreshStateTextView; // 上拉頭 private View loadmoreView; // 上拉的箭頭 private View pullUpView; // 正在載入的圖示 private View loadingView; // 載入結果圖示 private View loadStateImageView; // 載入結果:成功或失敗 private TextView loadStateTextView; // 實現了Pullable介面的View private View pullableView; // 過濾多點觸碰 private int mEvents; // 這兩個變數用來控制pull的方向,如果不加控制,當情況滿足可上拉又可下拉時沒法下拉 private boolean canPullDown = true; private boolean canPullUp = true; private TextView mHeaderTimeView; private TextView mHeaderTimeViewTitle; /** * 執行自動回滾的handler */ Handler updateHandler = new Handler() { @Override public void handleMessage(Message msg) { // 回彈速度隨下拉距離moveDeltaY增大而增大 MOVE_SPEED = (float) (8 + 5 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY)))); if (!isTouch) { // 正在重新整理,且沒有往上推的話則懸停,顯示"正在重新整理..." if (state == REFRESHING && pullDownY <= refreshDist) { pullDownY = refreshDist; timer.cancel(); } else if (state == LOADING && -pullUpY <= loadmoreDist) { pullUpY = -loadmoreDist; timer.cancel(); } } if (pullDownY > 0) pullDownY -= MOVE_SPEED; else if (pullUpY < 0) pullUpY += MOVE_SPEED; if (pullDownY < 0) { // 已完成回彈 pullDownY = 0; pullView.clearAnimation(); // 隱藏下拉頭時有可能還在重新整理,只有當前狀態不是正在重新整理時才改變狀態 if (state != REFRESHING && state != LOADING) changeState(INIT); timer.cancel(); } if (pullUpY > 0) { // 已完成回彈 pullUpY = 0; pullUpView.clearAnimation(); // 隱藏下拉頭時有可能還在重新整理,只有當前狀態不是正在重新整理時才改變狀態 if (state != REFRESHING && state != LOADING) changeState(INIT); timer.cancel(); } // 重新整理佈局,會自動呼叫onLayout requestLayout(); } }; public void setOnRefreshListener(OnRefreshListener listener) { mListener = listener; } public PullToRefreshLayout(Context context) { super(context); initView(context); } public PullToRefreshLayout(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(context); } private void initView(Context context) { timer = new MyTimer(updateHandler); rotateAnimation = (RotateAnimation) AnimationUtils.loadAnimation( context, R.anim.reverse_anim); refreshingAnimation = (RotateAnimation) AnimationUtils.loadAnimation( context, R.anim.rotating); // 新增勻速轉動動畫 LinearInterpolator lir = new LinearInterpolator(); rotateAnimation.setInterpolator(lir); refreshingAnimation.setInterpolator(lir); } private void hide() { timer.schedule(5); } /** * 完成重新整理操作,顯示重新整理結果。注意:重新整理完成後一定要呼叫這個方法 */ /** * @param refreshResult * PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失敗 */ public void refreshFinish(int refreshResult) { refreshingView.clearAnimation(); refreshingView.setVisibility(View.GONE); switch (refreshResult) { case SUCCEED: // 重新整理成功 refreshStateImageView.setVisibility(View.VISIBLE); refreshStateTextView.setText(R.string.refresh_succeed); refreshStateImageView .setBackgroundResource(R.drawable.refresh_succeed); break; case FAIL: default: // 重新整理失敗 refreshStateImageView.setVisibility(View.VISIBLE); refreshStateTextView.setText(R.string.refresh_fail); refreshStateImageView .setBackgroundResource(R.drawable.refresh_failed); break; } // 重新整理結果停留1秒 new Handler() { @Override public void handleMessage(Message msg) { changeState(DONE); hide(); } }.sendEmptyMessageDelayed(0, 1000); } /** * 載入完畢,顯示載入結果。注意:載入完成後一定要呼叫這個方法 * * @param refreshResult * PullToRefreshLayout.SUCCEED代表成功,PullToRefreshLayout.FAIL代表失敗 */ public void loadmoreFinish(int refreshResult) { loadingView.clearAnimation(); loadingView.setVisibility(View.GONE); switch (refreshResult) { case SUCCEED: // 載入成功 loadStateImageView.setVisibility(View.VISIBLE); loadStateTextView.setText(R.string.load_succeed); loadStateImageView.setBackgroundResource(R.drawable.load_succeed); break; case FAIL: default: // 載入失敗 loadStateImageView.setVisibility(View.VISIBLE); loadStateTextView.setText(R.string.load_fail); loadStateImageView.setBackgroundResource(R.drawable.load_failed); break; } // 重新整理結果停留1秒 new Handler() { @Override public void handleMessage(Message msg) { changeState(DONE); hide(); } }.sendEmptyMessageDelayed(0, 1000); } private void changeState(int to) { state = to; switch (state) { case INIT: // 下拉布局初始狀態 refreshStateImageView.setVisibility(View.GONE); refreshStateTextView.setText(R.string.pull_to_refresh); pullView.clearAnimation(); pullView.setVisibility(View.VISIBLE); // 上拉布局初始狀態 loadStateImageView.setVisibility(View.GONE); loadStateTextView.setText(R.string.pullup_to_load); pullUpView.clearAnimation(); pullUpView.setVisibility(View.VISIBLE); break; case RELEASE_TO_REFRESH: // 釋放重新整理狀態 refreshStateTextView.setText(R.string.release_to_refresh); pullView.startAnimation(rotateAnimation); break; case REFRESHING: // 正在重新整理狀態 pullView.clearAnimation(); refreshingView.setVisibility(View.VISIBLE); pullView.setVisibility(View.INVISIBLE); refreshingView.startAnimation(refreshingAnimation); refreshStateTextView.setText(R.string.refreshing); break; case RELEASE_TO_LOAD: // 釋放載入狀態 loadStateTextView.setText(R.string.release_to_load); pullUpView.startAnimation(rotateAnimation); break; case LOADING: // 正在載入狀態 pullUpView.clearAnimation(); loadingView.setVisibility(View.VISIBLE); pullUpView.setVisibility(View.INVISIBLE); loadingView.startAnimation(refreshingAnimation); loadStateTextView.setText(R.string.loading); break; case DONE: // 重新整理或載入完畢,啥都不做 break; } } /** * 不限制上拉或下拉 */ private void releasePull() { canPullDown = true; canPullUp = true; } /* * (非 Javadoc)由父控制元件決定是否分發事件,防止事件衝突 * * @see android.view.ViewGroup#dispatchTouchEvent(android.view.MotionEvent) */ @Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getActionMasked()) { case MotionEvent.ACTION_DOWN: downY = ev.getY(); lastY = downY; timer.cancel(); mEvents = 0; releasePull(); break; case MotionEvent.ACTION_POINTER_DOWN: case MotionEvent.ACTION_POINTER_UP: // 過濾多點觸碰 mEvents = -1; break; case MotionEvent.ACTION_MOVE: if (mEvents == 0) { if (((Pullable) pullableView).canPullDown() && canPullDown && state != LOADING) { // 可以下拉,正在載入時不能下拉 // 對實際滑動距離做縮小,造成用力拉的感覺 pullDownY = pullDownY + (ev.getY() - lastY) / radio; if (pullDownY < 0) { pullDownY = 0; canPullDown = false; canPullUp = true; } if (pullDownY > getMeasuredHeight()) pullDownY = getMeasuredHeight(); if (state == REFRESHING) { // 正在重新整理的時候觸控移動 isTouch = true; } } else if (((Pullable) pullableView).canPullUp() && canPullUp && state != REFRESHING) { // 可以上拉,正在重新整理時不能上拉 pullUpY = pullUpY + (ev.getY() - lastY) / radio; if (pullUpY > 0) { pullUpY = 0; canPullDown = true; canPullUp = false; } if (pullUpY < -getMeasuredHeight()) pullUpY = -getMeasuredHeight(); if (state == LOADING) { // 正在載入的時候觸控移動 isTouch = true; } } else releasePull(); } else mEvents = 0; lastY = ev.getY(); // 根據下拉距離改變比例 radio = (float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY + Math.abs(pullUpY)))); requestLayout(); if (pullDownY <= refreshDist && state == RELEASE_TO_REFRESH) { // 如果下拉距離沒達到重新整理的距離且當前狀態是釋放重新整理,改變狀態為下拉重新整理 changeState(INIT); } if (pullDownY >= refreshDist && state == INIT) { // 如果下拉距離達到重新整理的距離且當前狀態是初始狀態重新整理,改變狀態為釋放重新整理 changeState(RELEASE_TO_REFRESH); } // 下面是判斷上拉載入的,同上,注意pullUpY是負值 if (-pullUpY <= loadmoreDist && state == RELEASE_TO_LOAD) { changeState(INIT); } if (-pullUpY >= loadmoreDist && state == INIT) { changeState(RELEASE_TO_LOAD); } // 因為重新整理和載入操作不能同時進行,所以pullDownY和pullUpY不會同時不為0,因此這裡用(pullDownY + // Math.abs(pullUpY))就可以不對當前狀態作區分了 if ((pullDownY + Math.abs(pullUpY)) > 8) { // 防止下拉過程中誤觸發長按事件和點選事件 ev.setAction(MotionEvent.ACTION_CANCEL); } break; case MotionEvent.ACTION_UP: if (pullDownY > refreshDist || -pullUpY > loadmoreDist) // 正在重新整理時往下拉(正在載入時往上拉),釋放後下拉頭(上拉頭)不隱藏 isTouch = false; if (state == RELEASE_TO_REFRESH) { changeState(REFRESHING); // 重新整理操作 if (mListener != null) mListener.onRefresh(this); } else if (state == RELEASE_TO_LOAD) { changeState(LOADING); // 載入操作 if (mListener != null) mListener.onLoadMore(this); } hide(); default: break; } // 事件分發交給父類 super.dispatchTouchEvent(ev); return true; } private void initView() { // 初始化下拉布局 pullView = refreshView.findViewById(R.id.pull_icon); refreshStateTextView = (TextView) refreshView .findViewById(R.id.state_tv); refreshingView = refreshView.findViewById(R.id.refreshing_icon); refreshStateImageView = refreshView.findViewById(R.id.state_iv); mHeaderTimeView = (TextView) refreshView .findViewById(R.id.pull_to_refresh_header_time); mHeaderTimeViewTitle = (TextView) refreshView .findViewById(R.id.pull_to_refresh_last_update_time_text); // 初始化上拉布局 pullUpView = loadmoreView.findViewById(R.id.pullup_icon); loadStateTextView = (TextView) loadmoreView .findViewById(R.id.loadstate_tv); loadingView = loadmoreView.findViewById(R.id.loading_icon); loadStateImageView = loadmoreView.findViewById(R.id.loadstate_iv); } /** * 設定最近更新時間 * * @param label */ public void setLastUpdatedLabel(CharSequence label) { // 如果最後更新的時間的文字是空的話,隱藏前面的標題 mHeaderTimeViewTitle .setVisibility(TextUtils.isEmpty(label) ? View.INVISIBLE : View.VISIBLE); mHeaderTimeView.setText(label); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (!isLayout) { // 這裡是第一次進來的時候做一些初始化 refreshView = getChildAt(0); pullableView = getChildAt(1); loadmoreView = getChildAt(2); isLayout = true; initView(); refreshDist = ((ViewGroup) refreshView).getChildAt(0) .getMeasuredHeight(); loadmoreDist = ((ViewGroup) loadmoreView).getChildAt(0) .getMeasuredHeight(); } // 改變子控制元件的佈局,這裡直接用(pullDownY + pullUpY)作為偏移量,這樣就可以不對當前狀態作區分 refreshView.layout(0, (int) (pullDownY + pullUpY) - refreshView.getMeasuredHeight(), refreshView.getMeasuredWidth(), (int) (pullDownY + pullUpY)); pullableView.layout(0, (int) (pullDownY + pullUpY), pullableView.getMeasuredWidth(), (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight()); loadmoreView.layout(0, (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight(), loadmoreView.getMeasuredWidth(), (int) (pullDownY + pullUpY) + pullableView.getMeasuredHeight() + loadmoreView.getMeasuredHeight()); } class MyTimer { private Handler handler; private Timer timer; private MyTask mTask; public MyTimer(Handler handler) { this.handler = handler; timer = new Timer(); } public void schedule(long period) { if (mTask != null) { mTask.cancel(); mTask = null; } mTask = new MyTask(handler); timer.schedule(mTask, 0, period); } public void cancel() { if (mTask != null) { mTask.cancel(); mTask = null; } } class MyTask extends TimerTask { private Handler handler; public MyTask(Handler handler) { this.handler = handler; } @Override public void run() { handler.obtainMessage().sendToTarget(); } } } /** * 重新整理載入回撥介面 * * @author chenjing * */ public interface OnRefreshListener { /** * 重新整理操作 */ void onRefresh(PullToRefreshLayout pullToRefreshLayout); /** * 載入操作 */ void onLoadMore(PullToRefreshLayout pullToRefreshLayout); } }
public interface Pullable
{
/**
* 判斷是否可以下拉,如果不需要下拉功能可以直接return false
*
* @return true如果可以下拉否則返回false
*/
boolean canPullDown();
/**
* 判斷是否可以上拉,如果不需要上拉功能可以直接return false
*
* @return true如果可以上拉否則返回false
*/
boolean canPullUp();
}
public class PullableScrollView extends ScrollView implements Pullable
{
public PullableScrollView(Context context)
{
super(context);
}
public PullableScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public PullableScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public boolean canPullDown()
{
if (getScrollY() == 0)
return true;
else
return false;
}
@Override
public boolean canPullUp()
{
if (getScrollY() >= (getChildAt(0).getHeight() - getMeasuredHeight()))
return true;
else
return false;
}
}
封裝的可以下拉重新整理,上拉更多的scrollview網上有很多原始碼,這段鄙人也是參考網上的原始碼的這裡我就不再更多的描述了。