1. 程式人生 > >自定義ListView重新整理,上拉載入

自定義ListView重新整理,上拉載入

XListView

public class XListView extends ListView implements OnScrollListener {

   private float mLastY = -1; // save event y
   private Scroller mScroller; // 用於回滾
   private OnScrollListener mScrollListener; // 回滾監聽

   // 觸發重新整理和載入更多介面.
   private IXListViewListener mListViewListener;

   // -- 頭部的View
private XListViewHeader mHeaderView; // 檢視頭部的內容,用它計算頭部高度,和隱藏它 // 當禁用的時候重新整理 private RelativeLayout mHeaderViewContent; private TextView mHeaderTimeView; private int mHeaderViewHeight; // 頭部View的高 private boolean mEnablePullRefresh = true; private boolean mPullRefreshing = false; // 是否重新整理.
// -- 底部的View private XListViewFooter mFooterView; private boolean mEnablePullLoad; private boolean mPullLoading; private boolean mIsFooterReady = false; // 總列表項,用於檢測列表檢視的底部 private int mTotalItemCount; // for mScroller, 滾動頁首或者頁尾 private int mScrollBack; private final static int
SCROLLBACK_HEADER = 0;// 頂部 private final static int SCROLLBACK_FOOTER = 1;// 下部 private final static int SCROLL_DURATION = 400; // 滾動回時間 private final static int PULL_LOAD_MORE_DELTA = 50; // 當大於50PX的時候,載入更多 private final static float OFFSET_RADIO = 1.8f; // support iOS like pull // feature. /** * @param context */ public XListView(Context context) { super(context); initWithContext(context); } public XListView(Context context, AttributeSet attrs) { super(context, attrs); initWithContext(context); } public XListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initWithContext(context); } private void initWithContext(Context context) { mScroller = new Scroller(context, new DecelerateInterpolator()); // XListView need the scroll event, and it will dispatch the event to // user's listener (as a proxy). super.setOnScrollListener(this); // 初始化頭部View mHeaderView = new XListViewHeader(context); mHeaderViewContent = (RelativeLayout) mHeaderView .findViewById(R.id.xlistview_header_content); mHeaderTimeView = (TextView) mHeaderView .findViewById(R.id.xlistview_header_time); addHeaderView(mHeaderView);// 把頭部這個檢視新增進去 // 初始化底部的View mFooterView = new XListViewFooter(context); // 初始化頭部高度 mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { mHeaderViewHeight = mHeaderViewContent.getHeight(); getViewTreeObserver() .removeGlobalOnLayoutListener(this); } }); } /** * 啟用或禁用載入更多的功能. * * @param enable */ public void setPullLoadEnable(boolean enable) { mEnablePullLoad = enable; if (!mEnablePullLoad) { mFooterView.hide();// 隱藏 mFooterView.setOnClickListener(null); } else { mPullLoading = false; mFooterView.hide();// 顯示 mFooterView.setState(XListViewFooter.STATE_NORMAL); // both "上拉" 和 "點選" 將呼叫載入更多. mFooterView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startLoadMore(); } }); } } /** * 停止重新整理, 重置頭檢視. */ public void stopRefresh() { if (mPullRefreshing == true) { mPullRefreshing = false; resetHeaderHeight(); } } /** * stop load more, reset footer view. */ public void stopLoadMore() { if (mPullLoading == true) { mPullLoading = false; mFooterView.setState(XListViewFooter.STATE_NORMAL); } } /** * 設定最後一次重新整理時間 * * @param time */ public void setRefreshTime(String time) { mHeaderTimeView.setText(time); } private void invokeOnScrolling() { if (mScrollListener instanceof OnXScrollListener) { OnXScrollListener l = (OnXScrollListener) mScrollListener; l.onXScrolling(this); } } private void updateHeaderHeight(float delta) { mHeaderView.setVisiableHeight((int) delta + mHeaderView.getVisiableHeight()); if (mEnablePullRefresh && !mPullRefreshing) { // 未處於重新整理狀態,更新箭頭 if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) { mHeaderView.setState(XListViewHeader.STATE_READY); } else { mHeaderView.setState(XListViewHeader.STATE_NORMAL); } } setSelection(0); // scroll to top each time } /** * 重置頭檢視的高度 */ private void resetHeaderHeight() { int height = mHeaderView.getVisiableHeight(); if (height == 0) // 不顯示. return; // 不顯示重新整理和標題的時候,什麼都不顯示 if (mPullRefreshing && height <= mHeaderViewHeight) { return; } int finalHeight = 0; // 預設:滾動回頭. // 當滾動回顯示所有頭標題時候,重新整理 if (mPullRefreshing && height > mHeaderViewHeight) { finalHeight = mHeaderViewHeight; } mScrollBack = SCROLLBACK_HEADER; mScroller.startScroll(0, height, 0, finalHeight - height, SCROLL_DURATION); // 觸發重新整理 invalidate(); } // 改變底部檢視高度 private void updateFooterHeight(float delta) { int height = mFooterView.getBottomMargin() + (int) delta; if (mEnablePullLoad && !mPullLoading) { if (height > PULL_LOAD_MORE_DELTA) { // 高度足以呼叫載入更多 mFooterView.setState(XListViewFooter.STATE_READY); } else { mFooterView.setState(XListViewFooter.STATE_NORMAL); } } mFooterView.setBottomMargin(height); // setSelection(mTotalItemCount - 1); // scroll to bottom } private void resetFooterHeight() { int bottomMargin = mFooterView.getBottomMargin(); if (bottomMargin > 0) { mScrollBack = SCROLLBACK_FOOTER; mScroller.startScroll(0, bottomMargin, 0, -bottomMargin, SCROLL_DURATION); invalidate(); } } // 開始載入更多 private void startLoadMore() { mPullLoading = true; mFooterView.setState(XListViewFooter.STATE_LOADING); if (mListViewListener != null) { mListViewListener.onLoadMore(); } } // 觸發事件 @Override public boolean onTouchEvent(MotionEvent ev) { if (mLastY == -1) { mLastY = ev.getRawY(); } switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: mLastY = ev.getRawY(); break; case MotionEvent.ACTION_MOVE: final float deltaY = ev.getRawY() - mLastY; mLastY = ev.getRawY(); // System.out.println("資料監測:" + getFirstVisiblePosition() + "---->" // + getLastVisiblePosition()); if (getFirstVisiblePosition() == 0 && (mHeaderView.getVisiableHeight() > 0 || deltaY > 0)) { // 第一項顯示,標題顯示或拉下來. updateHeaderHeight(deltaY / OFFSET_RADIO); invokeOnScrolling(); } else if (getLastVisiblePosition() == mTotalItemCount - 1 && (mFooterView.getBottomMargin() > 0 || deltaY < 0)) { // 最後一頁,已停止或者想拉起 updateFooterHeight(-deltaY / OFFSET_RADIO); } break; default: mLastY = -1; // 重置 if (getFirstVisiblePosition() == 0) { // 呼叫重新整理,如果頭部檢視高度大於設定高度。 if (mEnablePullRefresh && mHeaderView.getVisiableHeight() > mHeaderViewHeight) { mPullRefreshing = true;// 那麼重新整理 mHeaderView.setState(XListViewHeader.STATE_REFRESHING); if (mListViewListener != null) { mListViewListener.onRefresh(); } } resetHeaderHeight();// 重新整理完畢,重置頭部高度,也就是返回上不 } if (getLastVisiblePosition() == mTotalItemCount - 1) { // 呼叫載入更多. if (mEnablePullLoad && mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA) { startLoadMore();// 如果底部檢視高度大於可以載入高度,那麼就開始載入 } resetFooterHeight();// 重置載入更多檢視高度 } break; } return super.onTouchEvent(ev); } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) { if (mScrollBack == SCROLLBACK_HEADER) { mHeaderView.setVisiableHeight(mScroller.getCurrY()); } else { mFooterView.setBottomMargin(mScroller.getCurrY()); } postInvalidate(); invokeOnScrolling(); } super.computeScroll(); } @Override public void setOnScrollListener(OnScrollListener l) { mScrollListener = l; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (mScrollListener != null) { mScrollListener.onScrollStateChanged(view, scrollState); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // 傳送到使用者的監聽器 mTotalItemCount = totalItemCount; if (mScrollListener != null) { mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } } public void setXListViewListener(IXListViewListener l) { mListViewListener = l; } /** * 你可以監聽到列表檢視,OnScrollListener 或者這個. 他將會被呼叫 , 當頭部或底部觸發的時候 */ public interface OnXScrollListener extends OnScrollListener { public void onXScrolling(View view); } /** * 實現這個介面來重新整理/負載更多的事件 */ public interface IXListViewListener { public void onRefresh(); public void onLoadMore(); } }



頭部重新整理

public class XListViewHeader extends LinearLayout {
   private LinearLayout mContainer;
   private ImageView mArrowImageView;
   private ProgressBar mProgressBar;
   private TextView mHintTextView;
   private int mState = STATE_NORMAL;// 初始狀態

   private Animation mRotateUpAnim;
   private Animation mRotateDownAnim;

   private final int ROTATE_ANIM_DURATION = 180;

   public final static int STATE_NORMAL = 0;
   public final static int STATE_READY = 1;
   public final static int STATE_REFRESHING = 2;

   public XListViewHeader(Context context) {
      super(context);
      initView(context);
   }

   /**
    * @param context
    * @param attrs
    */
   public XListViewHeader(Context context, AttributeSet attrs) {
      super(context, attrs);
      initView(context);
   }

   private void initView(Context context) {
      // 初始情況,設定下拉重新整理view高度為0
      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LayoutParams.FILL_PARENT, 0);
      // 時間TextView
      mContainer = (LinearLayout) LayoutInflater.from(context).inflate(
            R.layout.xlistview_header, null);
      addView(mContainer, lp);
      setGravity(Gravity.BOTTOM);
      // 找到頭部頁面裡的控制元件
      mArrowImageView = (ImageView) findViewById(R.id.xlistview_header_arrow);
      mHintTextView = (TextView) findViewById(R.id.xlistview_header_hint_textview);
      mProgressBar = (ProgressBar) findViewById(R.id.xlistview_header_progressbar);

      mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
      mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
      mRotateUpAnim.setFillAfter(true);
      mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
            0.5f);
      mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
      mRotateDownAnim.setFillAfter(true);
   }

   // 設定狀態
   public void setState(int state) {
      if (state == mState)
         return;

      if (state == STATE_REFRESHING) { // 顯示進度
         mArrowImageView.clearAnimation();
         mArrowImageView.setVisibility(View.INVISIBLE);// 不顯示圖片
         mProgressBar.setVisibility(View.VISIBLE);// 顯示進度條
      } else { // 顯示箭頭圖片
         mArrowImageView.setVisibility(View.VISIBLE);
         mProgressBar.setVisibility(View.INVISIBLE);
      }

      switch (state) {
         case STATE_NORMAL:
            if (mState == STATE_READY) {// 當狀態時準備的時候,顯示動畫
               mArrowImageView.startAnimation(mRotateDownAnim);
            }
            if (mState == STATE_REFRESHING) {// 當狀態顯示進度條的時候,清除動畫
               mArrowImageView.clearAnimation();
            }
            mHintTextView.setText("下拉重新整理");// 文字提示:下拉重新整理
            break;
         case STATE_READY:
            if (mState != STATE_READY) {
               mArrowImageView.clearAnimation();
               mArrowImageView.startAnimation(mRotateUpAnim);
               mHintTextView.setText("鬆開重新整理資料");// 鬆開重新整理資料
            }
            break;
         case STATE_REFRESHING:
            mHintTextView.setText("載入中...");
            break;
         default:
      }

      mState = state;
   }

   public void setVisiableHeight(int height) {
      if (height < 0)
         height = 0;
      LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer
            .getLayoutParams();
      lp.height = height;
      mContainer.setLayoutParams(lp);
   }

   public int getVisiableHeight() {
      return mContainer.getHeight();
   }

}

佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="bottom" >

    <RelativeLayout
        android:id="@+id/xlistview_header_content"
        android:layout_width="fill_parent"
        android:layout_height="60dp" >

        <LinearLayout
            android:id="@+id/xlistview_header_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/xlistview_header_hint_textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="下拉重新整理" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dp" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="最後更新時間:"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/xlistview_header_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/xlistview_header_arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-35dp"
            android:src="@drawable/xlistview_arrow" />

        <ProgressBar
            android:id="@+id/xlistview_header_progressbar"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-40dp"
            android:indeterminateDrawable="@drawable/listview_loading_github"
          android:indeterminateDuration="1800"
            android:visibility="invisible" />
    </RelativeLayout>

</LinearLayout>


上拉載入更多

public class XListViewFooter extends LinearLayout {
   public final static int STATE_NORMAL = 0;
   public final static int STATE_READY = 1;
   public final static int STATE_LOADING = 2;

   private Context mContext;

   private View mContentView;
   private View mProgressBar;
   private TextView mHintView;

   public XListViewFooter(Context context) {
      super(context);
      initView(context);
   }

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

   public void setState(int state) {
      mHintView.setVisibility(View.INVISIBLE);// 開始底部控制元件都隱藏
      mProgressBar.setVisibility(View.INVISIBLE);
      mHintView.setVisibility(View.INVISIBLE);
      if (state == STATE_READY) {// 如果是第一頁狀態,那麼“檢視更多”顯示
         mHintView.setVisibility(View.VISIBLE);
         mHintView.setText("鬆開顯示更多");// 鬆開顯示更多
      } else if (state == STATE_LOADING) {// 當載入的時候
         mProgressBar.setVisibility(View.VISIBLE);// 載入進度條顯示
      } else {
         mHintView.setVisibility(View.VISIBLE);
         mHintView.setText("檢視更多");// 檢視更多
      }
   }

   public void setBottomMargin(int height) {
      if (height < 0)
         return;
      LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContentView
            .getLayoutParams();
      lp.bottomMargin = height;
      mContentView.setLayoutParams(lp);
   }

   public int getBottomMargin() {
      LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContentView
            .getLayoutParams();
      return lp.bottomMargin;
   }

   /**
    * normal status
    */
   public void normal() {
      mHintView.setVisibility(View.VISIBLE);
      mProgressBar.setVisibility(View.GONE);
   }

   /**
    * loading status
    */
   public void loading() {
      mHintView.setVisibility(View.GONE);
      mProgressBar.setVisibility(View.VISIBLE);
   }

   /**
    * 當禁用拉載入更多隱藏底部檢視
    */
   public void hide() {
      LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContentView
            .getLayoutParams();
      lp.height = 0;
      mContentView.setLayoutParams(lp);
   }