1. 程式人生 > >Android中實現下拉重新整理

Android中實現下拉重新整理

需求:專案中的訊息列表介面要求實現類似sina微博的下拉重新整理;

思路:一般的訊息列表為ListView型別,將list載入到adapter中,再將adapter載入到ListView中,從而實現訊息列表的展示。而下拉重新整理要求給訊息列表加一個頭部,其中有圖片(向上/向下箭頭)和提示字樣(下拉重新整理/鬆開重新整理),從而我們需要做的事情:1.需要做一個head.xm來實現頭部的樣式定義;2.需要自定義一個繼承了ListView的MsgListView,在該類中將head加在MsgListView物件的頭部;3.將原有的訊息介面佈局檔案中的ListView改為cn.xd.microblogging.tools.MsgListView(包名.MsgListView);4.將原有的訊息介面後臺程式碼中建立的ListView物件改為MsgListView物件,注意訊息介面Activity要繼承ListActivity,並且實現其重新整理監聽。

說明:實現下拉重新整理很簡單,僅需要4個檔案:MsgRcvListActivity.java(訊息列表介面的後臺檔案,真正的重新整理動作在這裡完成,下拉重新整理相關code下面列出),msgrcvlistactivity.xml(訊息列表介面的前臺檔案,下拉重新整理相關code下面列出),MsgListView.java(本檔案拿來主義即可不用改,下拉重新整理自定義的列表類,監聽並執行下拉重新整理、鬆開重新整理、正在重新整理、完成重新整理等狀態的改變,但真正的重新整理動作不在這裡完成,完整code下面列出),head.xml(本檔案拿來主義即可不用改,下拉重新整理的樣式定義檔案,包括向上、向下箭頭,重新整理狀態提示等,完整code下面列出);

效果

程式碼

1.MsgRcvListActivity.java :

public class MsgRcvListActivity extends ListActivity {//注意:要繼承ListActivity
	…………//變數定義,略
	MsgListView list;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.msgrcvlistactivity);	
		list=(MsgListView)findViewById(android.R.id.list);//繼承ListActivity,id要寫成android.R.id.list,否則報異常
		…………//其他程式碼,略
    	           //重新整理監聽,此處實現真正重新整理
	           list.setonRefreshListener(new OnRefreshListener() {
			public void onRefresh() {
				new AsyncTask<Void, Void, Void>() {
					protected Void doInBackground(Void... params) {
						try {
							Thread.sleep(1000);
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						adapter.notifyDataSetChanged();
						new MsgLoad().execute();//重新整理監聽中,真正執行重新整理動作
						list.onRefreshComplete();
					}
				}.execute(null);
			}
		});
		list.setItemsCanFocus(false);            
		list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	}
	…………//其他程式碼,略
	public class MsgLoad extends AsyncTask<Void, Void, List<MsgBean>> {
		…………//其他程式碼,略
	}
}

2.msgrcvlistactivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <LinearLayout android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="#000000">       
	    //將ListView改為包名.自定義的列表類名,MsgListView.java程式碼見後,此程式碼不需改通用,下拉重新整理相關即此處,其他無關
	    <cn.xd.microblogging.tools.MsgListView
	    android:id="@android:id/list"
	    android:layout_height="wrap_content"
	    android:layout_width="fill_parent"
	    android:layout_weight="1.0"
	    android:drawSelectorOnTop="false"
	    android:scrollbars="vertical"
	    android:fadingEdgeLength="0dip" 
	    android:divider="@drawable/line"
	    android:dividerHeight="3.0dip"
	    android:cacheColorHint="#00000000" 
	    android:paddingBottom="40dp"/>
  </LinearLayout>
  <LinearLayout
      android:id="@+id/msg_list_load"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" >      
    <LinearLayout android:id="@android:id/empty"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent" >       
      <include
        android:id="@android:id/empty"
        layout="@layout/empty_loading"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />      
     </LinearLayout>
  </LinearLayout>
</RelativeLayout>

3.MsgListView.java,拷進專案基本不需改:

package cn.xd.microblogging.tools;

import java.util.Date;

import cn.xd.microblogging.R;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ProgressBar;
import android.widget.TextView;

/**
 * 
 * 自定義MsgListView,繼承了ListView,
 * 但填充了listview的頭部,即下拉重新整理樣式,並實現其功能
 * @author yanbo
 *
 */

public class MsgListView extends ListView implements OnScrollListener {
	 private final static int RELEASE_To_REFRESH = 0;
	 private final static int PULL_To_REFRESH = 1;
	 private final static int REFRESHING = 2;
	 private final static int DONE = 3;

	 private LayoutInflater inflater;

	 private LinearLayout headView; // 頭部

	 private TextView tipsTextview;//下拉重新整理
	 private TextView lastUpdatedTextView;//最新更新
	 private ImageView arrowImageView;//箭頭
	 private ProgressBar progressBar;//重新整理進度條

	 private RotateAnimation animation;//旋轉特效 重新整理中箭頭翻轉 向下變向上
	 private RotateAnimation reverseAnimation;

	 // 用於保證startY的值在一個完整的touch事件中只被記錄一次
	 private boolean isRecored;

	 private int headContentWidth;//頭部寬度
	 private int headContentHeight;//頭部高度

	 private int startY;//高度起始位置,用來記錄與頭部距離
	 private int firstItemIndex;//列表中首行索引,用來記錄其與頭部距離

	 private int state;//下拉重新整理中、鬆開重新整理中、正在重新整理中、完成重新整理

	 private boolean isBack;

	 public OnRefreshListener refreshListener;//重新整理監聽

	 private final static String TAG = "abc";

	 public MsgListView(Context context, AttributeSet attrs) {
	  super(context, attrs);
	  init(context);
	 }

	 private void init(Context context) {
	  inflater = LayoutInflater.from(context);

	  headView = (LinearLayout) inflater.inflate(R.layout.head, null);//listview拼接headview

	  arrowImageView = (ImageView) headView
	    .findViewById(R.id.head_arrowImageView);//headview中各view
	  arrowImageView.setMinimumWidth(50);
	  arrowImageView.setMinimumHeight(50);
	  progressBar = (ProgressBar) headView
	    .findViewById(R.id.head_progressBar);//headview中各view
	  tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);//headview中各view
	  lastUpdatedTextView = (TextView) headView
	    .findViewById(R.id.head_lastUpdatedTextView);//headview中各view

	  measureView(headView);
	  headContentHeight = headView.getMeasuredHeight();//頭部高度
	  headContentWidth = headView.getMeasuredWidth();//頭部寬度

	  headView.setPadding(0, -1 * headContentHeight, 0, 0);//setPadding(int left, int top, int right, int bottom) 
	  headView.invalidate();//Invalidate the whole view

	  Log.v("size", "width:" + headContentWidth + " height:"
	    + headContentHeight);

	  addHeaderView(headView);//新增進headview
	  setOnScrollListener(this);//滾動監聽

	  animation = new RotateAnimation(0, -180,
	    RotateAnimation.RELATIVE_TO_SELF, 0.5f,
	    RotateAnimation.RELATIVE_TO_SELF, 0.5f);
	  animation.setInterpolator(new LinearInterpolator());
	  animation.setDuration(250);
	  animation.setFillAfter(true);//特效animation設定

	  reverseAnimation = new RotateAnimation(-180, 0,
	    RotateAnimation.RELATIVE_TO_SELF, 0.5f,
	    RotateAnimation.RELATIVE_TO_SELF, 0.5f);
	  reverseAnimation.setInterpolator(new LinearInterpolator());
	  reverseAnimation.setDuration(250);
	  reverseAnimation.setFillAfter(true);//特效reverseAnimation設定
	 }

	 public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2,//滾動事件
	   int arg3) {
	  firstItemIndex = firstVisiableItem;//得到首item索引
	 }

	 public void onScrollStateChanged(AbsListView arg0, int arg1) {
	 }

	 public boolean onTouchEvent(MotionEvent event) {//觸控事件
	  switch (event.getAction()) {
	  case MotionEvent.ACTION_DOWN://手按下  對應下拉重新整理狀態
	   if (firstItemIndex == 0 && !isRecored) {//如果首item索引為0,且尚未記錄startY,則在下拉時記錄之,並執行isRecored = true;
	    startY = (int) event.getY();
	    isRecored = true;

	    Log.v(TAG, "在down時候記錄當前位置‘");
	   }
	   break;

	  case MotionEvent.ACTION_UP://手鬆開  對應鬆開重新整理狀態

	   if (state != REFRESHING) {//手鬆開有4個狀態:下拉重新整理、鬆開重新整理、正在重新整理、完成重新整理。如果當前不是正在重新整理
	    if (state == DONE) {//如果當前是完成重新整理,什麼都不做
	    }
	    if (state == PULL_To_REFRESH) {//如果當前是下拉重新整理,狀態設為完成重新整理(意即下拉重新整理中就鬆開了,實際未完成重新整理),執行changeHeaderViewByState()
	     state = DONE;
	     changeHeaderViewByState();

	     Log.v(TAG, "由下拉重新整理狀態,到done狀態");
	    }
	    if (state == RELEASE_To_REFRESH) {//如果當前是鬆開重新整理,狀態設為正在重新整理(意即鬆開重新整理中鬆開手,才是真正地重新整理),執行changeHeaderViewByState()
	     state = REFRESHING;
	     changeHeaderViewByState();
	     onRefresh();//真正重新整理,所以執行onrefresh,執行後狀態設為完成重新整理

	     Log.v(TAG, "由鬆開重新整理狀態,到done狀態");
	    }
	   }

	   isRecored = false;//手鬆開,則無論怎樣,可以重新記錄startY,因為只要手鬆開就認為一次重新整理已完成
	   isBack = false;

	   break;

	  case MotionEvent.ACTION_MOVE://手拖動,拖動過程中不斷地實時記錄當前位置
	   int tempY = (int) event.getY();
	   if (!isRecored && firstItemIndex == 0) {//如果首item索引為0,且尚未記錄startY,則在拖動時記錄之,並執行isRecored = true;
	    Log.v(TAG, "在move時候記錄下位置");
	    isRecored = true;
	    startY = tempY;
	   }
	   if (state != REFRESHING && isRecored) {//如果狀態不是正在重新整理,且已記錄startY:tempY為拖動過程中一直在變的高度,startY為拖動起始高度
	    // 可以鬆手去重新整理了
	    if (state == RELEASE_To_REFRESH) {//如果狀態是鬆開重新整理
	     // 往上推了,推到了螢幕足夠掩蓋head的程度,但是還沒有推到全部掩蓋的地步
	     if ((tempY - startY < headContentHeight)//如果實時高度大於起始高度,且兩者之差小於頭部高度,則狀態設為下拉重新整理
	       && (tempY - startY) > 0) {
	      state = PULL_To_REFRESH;
	      changeHeaderViewByState();

	      Log.v(TAG, "由鬆開重新整理狀態轉變到下拉重新整理狀態");
	     }
	     // 一下子推到頂了
	     else if (tempY - startY <= 0) {//如果實時高度小於等於起始高度了,則說明到頂了,狀態設為完成重新整理
	      state = DONE;
	      changeHeaderViewByState();

	      Log.v(TAG, "由鬆開重新整理狀態轉變到done狀態");
	     }
	     // 往下拉了,或者還沒有上推到螢幕頂部掩蓋head的地步
	     else {//如果當前拖動過程中既沒有到下拉重新整理的地步,也沒有到完成重新整理(到頂)的地步,則保持鬆開重新整理狀態
	      // 不用進行特別的操作,只用更新paddingTop的值就行了
	     }
	    }
	    // 還沒有到達顯示鬆開重新整理的時候,DONE或者是PULL_To_REFRESH狀態
	    if (state == PULL_To_REFRESH) {//如果狀態是下拉重新整理
	     // 下拉到可以進入RELEASE_TO_REFRESH的狀態
	     if (tempY - startY >= headContentHeight) {//如果實時高度與起始高度之差大於等於頭部高度,則狀態設為鬆開重新整理
	      state = RELEASE_To_REFRESH;
	      isBack = true;
	      changeHeaderViewByState();

	      Log.v(TAG, "由done或者下拉重新整理狀態轉變到鬆開重新整理");
	     }
	     // 上推到頂了
	     else if (tempY - startY <= 0) {//如果實時高度小於等於起始高度了,則說明到頂了,狀態設為完成重新整理
	      state = DONE;
	      changeHeaderViewByState();

	      Log.v(TAG, "由DOne或者下拉重新整理狀態轉變到done狀態");
	     }
	    }

	    // done狀態下
	    if (state == DONE) {//如果狀態是完成重新整理
	     if (tempY - startY > 0) {//如果實時高度大於起始高度了,則狀態設為下拉重新整理
	      state = PULL_To_REFRESH;
	      changeHeaderViewByState();
	     }
	    }

	    // 更新headView的size
	    if (state == PULL_To_REFRESH) {//如果狀態是下拉重新整理,更新headview的size           ?
	     headView.setPadding(0, -1 * headContentHeight
	       + (tempY - startY), 0, 0);
	     headView.invalidate();
	    }

	    // 更新headView的paddingTop
	    if (state == RELEASE_To_REFRESH) {//如果狀態是鬆開重新整理,更新 headview的paddingtop      ?
	     headView.setPadding(0, tempY - startY - headContentHeight,
	       0, 0);
	     headView.invalidate();
	    }
	   }
	   break;
	  }
	  return super.onTouchEvent(event);
	 }
	 
	 // 當狀態改變時候,呼叫該方法,以更新介面
	 private void changeHeaderViewByState() {
	  switch (state) {
	  case RELEASE_To_REFRESH:
	   arrowImageView.setVisibility(View.VISIBLE);
	   progressBar.setVisibility(View.GONE);
	   tipsTextview.setVisibility(View.VISIBLE);
	   lastUpdatedTextView.setVisibility(View.VISIBLE);

	   arrowImageView.clearAnimation();
	   arrowImageView.startAnimation(animation);

	   tipsTextview.setText("鬆開重新整理");

	   Log.v(TAG, "當前狀態,鬆開重新整理");
	   break;
	  case PULL_To_REFRESH:
	   progressBar.setVisibility(View.GONE);
	   tipsTextview.setVisibility(View.VISIBLE);
	   lastUpdatedTextView.setVisibility(View.VISIBLE);
	   arrowImageView.clearAnimation();
	   arrowImageView.setVisibility(View.VISIBLE);
	   // 是由RELEASE_To_REFRESH狀態轉變來的
	   if (isBack) {
	    isBack = false;
	    arrowImageView.clearAnimation();
	    arrowImageView.startAnimation(reverseAnimation);

	    tipsTextview.setText("下拉重新整理");
	   } else {
	    tipsTextview.setText("下拉重新整理");
	   }
	   Log.v(TAG, "當前狀態,下拉重新整理");
	   break;

	  case REFRESHING:

	   headView.setPadding(0, 0, 0, 0);
	   headView.invalidate();

	   progressBar.setVisibility(View.VISIBLE);
	   arrowImageView.clearAnimation();
	   arrowImageView.setVisibility(View.GONE);
	   tipsTextview.setText("正在重新整理...");
	   lastUpdatedTextView.setVisibility(View.VISIBLE);

	   Log.v(TAG, "當前狀態,正在重新整理...");
	   break;
	  case DONE:
	   headView.setPadding(0, -1 * headContentHeight, 0, 0);
	   headView.invalidate();

	   progressBar.setVisibility(View.GONE);
	   arrowImageView.clearAnimation();
	   arrowImageView
	     .setImageResource(R.drawable.ic_pulltorefresh_arrow);
	   tipsTextview.setText("下拉重新整理");
	   lastUpdatedTextView.setVisibility(View.VISIBLE);

	   Log.v(TAG, "當前狀態,done");
	   break;
	  }
	 }

	 public void setonRefreshListener(OnRefreshListener refreshListener) {
	  this.refreshListener = refreshListener;
	 }

	 public interface OnRefreshListener {
	  public void onRefresh();
	 }

	 public void onRefreshComplete() {
	  state = DONE;
	  lastUpdatedTextView.setText("最近更新:" + new Date().toLocaleString());//重新整理完成時,頭部提醒的重新整理日期
	  changeHeaderViewByState();
	 }

	 private void onRefresh() {
	  if (refreshListener != null) {
	   refreshListener.onRefresh();
	  }
	 }

	 //此方法直接照搬自網路上的一個下拉重新整理的demo,此處是“估計”headView的width以及height
	 private void measureView(View child) {
	  ViewGroup.LayoutParams p = child.getLayoutParams();
	  if (p == null) {
	   p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
	     ViewGroup.LayoutParams.WRAP_CONTENT);
	  }
	  int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
	  int lpHeight = p.height;
	  int childHeightSpec;
	  if (lpHeight > 0) {
	   childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
	     MeasureSpec.EXACTLY);
	  } else {
	   childHeightSpec = MeasureSpec.makeMeasureSpec(0,
	     MeasureSpec.UNSPECIFIED);
	  }
	  child.measure(childWidthSpec, childHeightSpec);
	 }
	}

4.head.xml,拷進專案基本不需改:

<?xml version="1.0" encoding="utf-8"?>
<!-- ListView的頭部 -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/head_rootLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
 <!-- 內容 -->
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/head_contentLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="30dp" >
        <!-- 箭頭影象、進度條 -->
        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true" >
            <!-- 箭頭 -->
            <ImageView
                android:id="@+id/head_arrowImageView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@drawable/ic_pulltorefresh_arrow" 
                android:contentDescription="@string/app_name"/>
            <!-- 進度條 -->
            <ProgressBar
                android:id="@+id/head_progressBar"
                style="?android:attr/progressBarStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:visibility="gone" />
        </FrameLayout>
        <!-- 提示、最近更新 -->
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:gravity="center_horizontal"
            android:orientation="vertical" >
            <!-- 提示 -->
            <TextView
                android:id="@+id/head_tipsTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/pulltorefresh"
                android:textColor="#ffffff"
                android:textSize="20sp" />
            <!-- 最近更新 -->
            <TextView
                android:id="@+id/head_lastUpdatedTextView"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/lastupdate"
                android:textColor="#cc6600"
                android:textSize="10sp" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

 殊途同歸,擴充套件借鑑其他下拉重新整理方式: