标签:
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:id="@+id/pull_to_refresh_head" 4 android:layout_width="fill_parent" 5 android:layout_height="60dip" > 6 <LinearLayout 7 android:layout_width="200dip" 8 android:layout_height="60dip" 9 android:layout_centerInParent="true" 10 android:orientation="horizontal" > 11 <RelativeLayout 12 android:layout_width="0dip" 13 android:layout_height="60dip" 14 android:layout_weight="3" 15 > 16 <ImageView 17 android:id="@+id/arrow" 18 android:layout_width="wrap_content" 19 android:layout_height="wrap_content" 20 android:layout_centerInParent="true" 21 android:src="@drawable/arrow" 22 /> 23 <ProgressBar 24 android:id="@+id/progress_bar" 25 android:layout_width="30dip" 26 android:layout_height="30dip" 27 android:layout_centerInParent="true" 28 android:visibility="gone" 29 /> 30 </RelativeLayout> 31 <LinearLayout 32 android:layout_width="0dip" 33 android:layout_height="60dip" 34 android:layout_weight="12" 35 android:orientation="vertical" > 36 <TextView 37 android:id="@+id/description" 38 android:layout_width="fill_parent" 39 android:layout_height="0dip" 40 android:layout_weight="1" 41 android:gravity="center_horizontal|bottom" 42 android:text="@string/pull_to_refresh" /> 43 <TextView 44 android:id="@+id/updated_at" 45 android:layout_width="fill_parent" 46 android:layout_height="0dip" 47 android:layout_weight="1" 48 android:gravity="center_horizontal|top" 49 android:text="@string/updated_at" /> 50 </LinearLayout> 51 </LinearLayout> 52 </RelativeLayout>
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 <string name="app_name">PullToRefreshTest</string> 4 <string name="pull_to_refresh">下拉可以刷新</string> 5 <string name="release_to_refresh">释放立即刷新</string> 6 <string name="refreshing">正在刷新…</string> 7 <string name="not_updated_yet">暂未更新过</string> 8 <string name="updated_at">上次更新于%1$s前</string> 9 <string name="updated_just_now">刚刚更新</string> 10 <string name="time_error">时间有问题</string> 11 </resources>
1 public class RefreshableView extends LinearLayout implements OnTouchListener { 2 //下拉状态 3 public static final int STATUS_PULL_TO_REFRESH = 0; 4 //释放立即刷新状态 5 public static final int STATUS_RELEASE_TO_REFRESH = 1 6 //正在刷新状态 7 public static final int STATUS_REFRESHING = 2; 8 //刷新完成或未刷新状态 9 public static final int STATUS_REFRESH_FINISHED = 3; 10 //下拉头部回滚的速度 11 public static final int SCROLL_SPEED = -20; 12 //一分钟的毫秒值,用于判断上次的更新时间 13 public static final long ONE_MINUTE = 60 * 1000; 14 //一小时的毫秒值,用于判断上次的更新时间 15 public static final long ONE_HOUR = 60 * ONE_MINUTE; 16 //一天的毫秒值,用于判断上次的更新时间 17 public static final long ONE_DAY = 24 * ONE_HOUR; 18 //一月的毫秒值,用于判断上次的更新时间 19 public static final long ONE_MONTH = 30 * ONE_DAY; 20 //一年的毫秒值,用于判断上次的更新时间 21 public static final long ONE_YEAR = 12 * ONE_MONTH; 22 //上次更新时间的字符串常量,用于作为SharedPreferences的键值 23 private static final String UPDATED_AT = "updated_at"; 24 //下拉刷新的回调接口 25 private PullToRefreshListener mListener; 26 //用于存储上次更新时间 27 private SharedPreferences preferences; 28 //下拉头的View 29 private View header; 30 //需要去下拉刷新的ListView 31 private ListView listView; 32 //刷新时显示的进度条 33 private ProgressBar progressBar; 34 //指示下拉和释放的箭头 35 private ImageView arrow; 36 //指示下拉和释放的文字描述 37 private TextView description; 38 //上次更新时间的文字描述 39 private TextView updateAt; 40 //下拉头的布局参数 41 private MarginLayoutParams headerLayoutParams; 42 //上次更新时间的毫秒值 43 private long lastUpdateTime; 44 //为了防止不同界面的下拉刷新在上次更新时间上互相有冲突,使用id来做区分 45 private int mId = -1; 46 //下拉头的高度 47 private int hideHeaderHeight; 48 //当前处理什么状态,可选值有STATUS_PULL_TO_REFRESH,STATUS_RELEASE_TO_REFRESH,STATUS_REFRESHING 和 STATUS_REFRESH_FINISHED 49 private int currentStatus = STATUS_REFRESH_FINISHED;; 50 //记录上一次的状态是什么,避免进行重复操作 51 private int lastStatus = currentStatus; 52 //手指按下时的屏幕纵坐标 53 private float yDown; 54 //在被判定为滚动之前用户手指可以移动的最大值。 55 private int touchSlop; 56 //是否已加载过一次layout,这里onLayout中的初始化只需加载一次 57 private boolean loadOnce; 58 //当前是否可以下拉,只有ListView滚动到头的时候才允许下拉 59 private boolean ableToPull; 60 61 //下拉刷新控件的构造函数,会在运行时动态添加一个下拉头的布局。 62 public RefreshableView(Context context, AttributeSet attrs) { 63 super(context, attrs); 64 preferences = PreferenceManager.getDefaultSharedPreferences(context); 65 header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true); 66 progressBar = (ProgressBar) header.findViewById(R.id.progress_bar); 67 arrow = (ImageView) header.findViewById(R.id.arrow); 68 description = (TextView) header.findViewById(R.id.description); 69 updateAt = (TextView) header.findViewById(R.id.updated_at); 70 touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); 71 refreshUpdatedAtValue(); 72 setOrientation(VERTICAL); 73 addView(header, 0); 74 } 75 76 //进行一些关键性的初始化操作,比如:将下拉头向上偏移进行隐藏,给ListView注册touch事件。 77 protected void onLayout(boolean changed, int l, int t, int r, int b) { 78 super.onLayout(changed, l, t, r, b); 79 if (changed && !loadOnce) { 80 hideHeaderHeight = -header.getHeight(); 81 headerLayoutParams = (MarginLayoutParams) header.getLayoutParams(); 82 headerLayoutParams.topMargin = hideHeaderHeight; 83 listView = (ListView) getChildAt(1); 84 listView.setOnTouchListener(this); 85 loadOnce = true; 86 } 87 } 88 89 //当ListView被触摸时调用,其中处理了各种下拉刷新的具体逻辑。 90 public boolean onTouch(View v, MotionEvent event) { 91 setIsAbleToPull(event); 92 if (ableToPull) { 93 switch (event.getAction()) { 94 case MotionEvent.ACTION_DOWN: 95 yDown = event.getRawY(); 96 break; 97 case MotionEvent.ACTION_MOVE: 98 float yMove = event.getRawY(); 99 int distance = (int) (yMove - yDown); 100 101 // 如果手指是下滑状态,并且下拉头是完全隐藏的,就屏蔽下拉事件 102 if (distance <= 0 && headerLayoutParams.topMargin <= hideHeaderHeight) { 103 return false; 104 } 105 if (distance < touchSlop) { 106 return false; 107 } 108 if (currentStatus != STATUS_REFRESHING) { 109 if (headerLayoutParams.topMargin > 0) { 110 currentStatus = STATUS_RELEASE_TO_REFRESH; 111 } else { 112 currentStatus = STATUS_PULL_TO_REFRESH; 113 } 114 115 // 通过偏移下拉头的topMargin值,来实现下拉效果 116 headerLayoutParams.topMargin = (distance / 2) + hideHeaderHeight; 117 header.setLayoutParams(headerLayoutParams); 118 } 119 break; 120 case MotionEvent.ACTION_UP: 121 default: 122 if (currentStatus == STATUS_RELEASE_TO_REFRESH) { 123 124 // 松手时如果是释放立即刷新状态,就去调用正在刷新的任务 125 new RefreshingTask().execute(); 126 } else if (currentStatus == STATUS_PULL_TO_REFRESH) { 127 128 // 松手时如果是下拉状态,就去调用隐藏下拉头的任务 129 new HideHeaderTask().execute(); 130 } 131 break; 132 } 133 134 // 时刻记得更新下拉头中的信息 135 if (currentStatus == STATUS_PULL_TO_REFRESH 136 || currentStatus == STATUS_RELEASE_TO_REFRESH) { 137 updateHeaderView(); 138 139 // 当前正处于下拉或释放状态,要让ListView失去焦点,否则被点击的那一项会一直处于选中状态 140 listView.setPressed(false); 141 listView.setFocusable(false); 142 listView.setFocusableInTouchMode(false); 143 lastStatus = currentStatus; 144 145 // 当前正处于下拉或释放状态,通过返回true屏蔽掉ListView的滚动事件 146 return true; 147 } 148 } 149 return false; 150 } 151 152 //给下拉刷新控件注册一个监听器。 153 154 //为了防止不同界面的下拉刷新在上次更新时间上互相有冲突, 请不同界面在注册下拉刷新监听器时一定要传入不同的id。 155 public void setOnRefreshListener(PullToRefreshListener listener, int id) { 156 mListener = listener; 157 mId = id; 158 } 159 160 // 当所有的刷新逻辑完成后,记录调用一下,否则你的ListView将一直处于正在刷新状态。 161 public void finishRefreshing() { 162 currentStatus = STATUS_REFRESH_FINISHED; 163 preferences.edit().putLong(UPDATED_AT + mId, System.currentTimeMillis()).commit(); 164 new HideHeaderTask().execute(); 165 } 166 167 //根据当前ListView的滚动状态来设定 {@link #ableToPull}的值,每次都需要在onTouch中第一个执行,这样可以判断出当前应该是滚动ListView,还是应该进行下拉。 168 private void setIsAbleToPull(MotionEvent event) { 169 View firstChild = listView.getChildAt(0); 170 if (firstChild != null) { 171 int firstVisiblePos = listView.getFirstVisiblePosition(); 172 if (firstVisiblePos == 0 && firstChild.getTop() == 0) { 173 if (!ableToPull) { 174 yDown = event.getRawY(); 175 } 176 177 // 如果首个元素的上边缘,距离父布局值为0,就说明ListView滚动到了最顶部,此时应该允许下拉刷新 178 ableToPull = true; 179 } else { 180 if (headerLayoutParams.topMargin != hideHeaderHeight) { 181 headerLayoutParams.topMargin = hideHeaderHeight; 182 header.setLayoutParams(headerLayoutParams); 183 } 184 ableToPull = false; 185 } 186 } else { 187 188 // 如果ListView中没有元素,也应该允许下拉刷新 189 ableToPull = true; 190 } 191 } 192 193 //更新下拉头中的信息。 194 private void updateHeaderView() { 195 if (lastStatus != currentStatus) { 196 if (currentStatus == STATUS_PULL_TO_REFRESH) { 197 description.setText(getResources().getString(R.string.pull_to_refresh)); 198 arrow.setVisibility(View.VISIBLE); 199 progressBar.setVisibility(View.GONE); 200 rotateArrow(); 201 } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) { 202 description.setText(getResources().getString(R.string.release_to_refresh)); 203 arrow.setVisibility(View.VISIBLE); 204 progressBar.setVisibility(View.GONE); 205 rotateArrow(); 206 } else if (currentStatus == STATUS_REFRESHING) { 207 description.setText(getResources().getString(R.string.refreshing)); 208 progressBar.setVisibility(View.VISIBLE); 209 arrow.clearAnimation(); 210 arrow.setVisibility(View.GONE); 211 } 212 refreshUpdatedAtValue(); 213 } 214 } 215 216 //根据当前的状态来旋转箭头。 217 private void rotateArrow() { 218 float pivotX = arrow.getWidth() / 2f; 219 float pivotY = arrow.getHeight() / 2f; 220 float fromDegrees = 0f; 221 float toDegrees = 0f; 222 if (currentStatus == STATUS_PULL_TO_REFRESH) { 223 fromDegrees = 180f; 224 toDegrees = 360f; 225 } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) { 226 fromDegrees = 0f; 227 toDegrees = 180f; 228 } 229 230 RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY); 231 animation.setDuration(100); 232 animation.setFillAfter(true); 233 arrow.startAnimation(animation); 234 } 235 236 //刷新下拉头中上次更新时间的文字描述。 237 private void refreshUpdatedAtValue() { 238 lastUpdateTime = preferences.getLong(UPDATED_AT + mId, -1); 239 long currentTime = System.currentTimeMillis(); 240 long timePassed = currentTime - lastUpdateTime; 241 long timeIntoFormat; 242 String updateAtValue; 243 if (lastUpdateTime == -1) { 244 updateAtValue = getResources().getString(R.string.not_updated_yet); 245 } else if (timePassed < 0) { 246 updateAtValue = getResources().getString(R.string.time_error); 247 } else if (timePassed < ONE_MINUTE) { 248 updateAtValue = getResources().getString(R.string.updated_just_now); 249 } else if (timePassed < ONE_HOUR) { 250 timeIntoFormat = timePassed / ONE_MINUTE; 251 String value = timeIntoFormat + "分钟"; 252 updateAtValue = String.format(getResources().getString(R.string.updated_at), value); 253 } else if (timePassed < ONE_DAY) { 254 timeIntoFormat = timePassed / ONE_HOUR; 255 String value = timeIntoFormat + "小时"; 256 updateAtValue = String.format(getResources().getString(R.string.updated_at), value); 257 } else if (timePassed < ONE_MONTH) { 258 timeIntoFormat = timePassed / ONE_DAY; 259 String value = timeIntoFormat + "天"; 260 updateAtValue = String.format(getResources().getString(R.string.updated_at), value); 261 } else if (timePassed < ONE_YEAR) { 262 timeIntoFormat = timePassed / ONE_MONTH; 263 String value = timeIntoFormat + "个月"; 264 updateAtValue = String.format(getResources().getString(R.string.updated_at), value); 265 } else { 266 timeIntoFormat = timePassed / ONE_YEAR; 267 String value = timeIntoFormat + "年"; 268 updateAtValue = String.format(getResources().getString(R.string.updated_at), value); 269 } 270 updateAt.setText(updateAtValue); 271 } 272 273 //正在刷新的任务,在此任务中会去回调注册进来的下拉刷新监听器。 274 class RefreshingTask extends AsyncTask<Void, Integer, Void> { 275 protected Void doInBackground(Void... params) { 276 int topMargin = headerLayoutParams.topMargin; 277 while (true) { 278 topMargin = topMargin + SCROLL_SPEED; 279 if (topMargin <= 0) { 280 topMargin = 0; 281 break; 282 } 283 publishProgress(topMargin); 284 sleep(10); 285 } 286 currentStatus = STATUS_REFRESHING; 287 publishProgress(0); 288 if (mListener != null) { 289 mListener.onRefresh(); 290 } 291 return null; 292 } 293 294 protected void onProgressUpdate(Integer... topMargin) { 295 updateHeaderView(); 296 headerLayoutParams.topMargin = topMargin[0]; 297 header.setLayoutParams(headerLayoutParams); 298 } 299 } 300 301 //隐藏下拉头的任务,当未进行下拉刷新或下拉刷新完成后,此任务将会使下拉头重新隐藏。 302 303 class HideHeaderTask extends AsyncTask<Void, Integer, Integer> { 304 protected Integer doInBackground(Void... params) { 305 int topMargin = headerLayoutParams.topMargin; 306 while (true) { 307 topMargin = topMargin + SCROLL_SPEED; 308 if (topMargin <= hideHeaderHeight) { 309 topMargin = hideHeaderHeight; 310 break; 311 } 312 publishProgress(topMargin); 313 sleep(10); 314 } 315 return topMargin; 316 } 317 318 protected void onProgressUpdate(Integer... topMargin) { 319 headerLayoutParams.topMargin = topMargin[0]; 320 header.setLayoutParams(headerLayoutParams); 321 } 322 323 protected void onPostExecute(Integer topMargin) { 324 headerLayoutParams.topMargin = topMargin; 325 header.setLayoutParams(headerLayoutParams); 326 currentStatus = STATUS_REFRESH_FINISHED; 327 } 328 } 329 330 //使当前线程睡眠指定的毫秒数。指定当前线程睡眠多久,以毫秒为单位 331 private void sleep(int time) { 332 try { 333 Thread.sleep(time); 334 } catch (InterruptedException e) { 335 e.printStackTrace(); 336 } 337 } 338 339 //下拉刷新的监听器,使用下拉刷新的地方应该注册此监听器来获取刷新回调。 340 public interface PullToRefreshListener { 341 342 //刷新时会去回调此方法,在方法内编写具体的刷新逻辑。注意此方法是在子线程中调用的, 你可以不必另开线程来进行耗时操作。 343 void onRefresh(); 344 } 345 }
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context=".MainActivity" > 6 7 <com.example.pulltorefreshtest.RefreshableView 8 android:id="@+id/refreshable_view" 9 android:layout_width="fill_parent" 10 android:layout_height="fill_parent" > 11 12 <ListView 13 android:id="@+id/list_view" 14 android:layout_width="fill_parent" 15 android:layout_height="fill_parent" > 16 </ListView> 17 18 </com.example.pulltorefreshtest.RefreshableView> 19 </RelativeLayout>
1 public class MainActivity extends Activity { 2 RefreshableView refreshableView; 3 ListView listView; 4 ArrayAdapter<String> adapter; 5 String[] items = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L" }; 6 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 requestWindowFeature(Window.FEATURE_NO_TITLE); 10 setContentView(R.layout.activity_main); 11 refreshableView = (RefreshableView) findViewById(R.id.refreshable_view); 12 listView = (ListView) findViewById(R.id.list_view); 13 adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items); 14 listView.setAdapter(adapter); 15 refreshableView.setOnRefreshListener(new PullToRefreshListener() { 16 17 public void onRefresh() { 18 try { 19 Thread.sleep(3000); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 refreshableView.finishRefreshing(); 24 } 25 }, 0); 26 } 27 }
标签:
原文地址:http://www.cnblogs.com/suannaibuding/p/5437944.html