[关闭]
@Tyhj 2017-06-29T06:08:14.000000Z 字数 12321 阅读 1599

Android自定义控件(一)——自定义下拉刷新控件

Android


原文:https://www.zybuluo.com/Tyhj/note/800026

自定义控件大家都会用,网上也一大堆,有些的确很炫酷,但是很难遇到在自己的项目中想要的效果。所以会一些基本的自定义控件还是必要的。我也是刚开始学习自定义控件,有兴趣的可以看看,交流,指出我的不足之处

下拉刷新控件是一个经常被自定义的控件,可以实现很炫的效果,一般情况,Google官方的SwipeRefreshLayout就很好用了,现在我要实现的效果如下:

gif可能有点慢,在实际效果很流畅的,显示效果也可能更好。
刚开始做自定义控件一开始就想自己从零实现真的难,所以先看看别人是怎么做的,然后自己照着模仿,改动,然后自己实现。我先看了郭霖的自定义ListView下拉刷新控件自己改的,然后了解了其中过程,基本上这类的下拉刷新效果自己去实现就没什么问题了。

实现思路:

这里我们将采取的方案是使用组合View的方式,先自定义一个布局继承自LinearLayout,然后在这个布局中加入下拉头和ListView这两个子元素,并让这两个子元素纵向排列。初始化的时候,让下拉头向上偏移出屏幕,这样我们看到的就只有ListView了。然后对ListView的touch事件进行监听,如果当前ListView已经滚动到顶部并且手指还在向下拉的话,那就将下拉头显示出来,松手后进行刷新操作,并将下拉头隐藏。原理示意图如下:

先新建一个布局作为下拉的头部:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:id="@+id/pull_to_refresh_head"
  3. android:layout_width="match_parent"
  4. android:layout_height="360dp">
  5. <LinearLayout
  6. android:layout_width="match_parent"
  7. android:layout_height="360dp"
  8. android:elevation="2dp"
  9. android:gravity="center">
  10. <ImageView
  11. android:id="@+id/iv_triangle"
  12. android:layout_width="40dp"
  13. android:layout_height="40dp"
  14. android:layout_marginTop="130dp"
  15. android:src="@mipmap/ic_triangle" />
  16. </LinearLayout>
  17. <ImageView
  18. android:layout_width="match_parent"
  19. android:layout_height="360dp"
  20. android:scaleType="centerCrop"
  21. android:src="@mipmap/bg_refresh" />
  22. </RelativeLayout>

里面很简单就是一个ImageView显示刷新的那个旋转的三角形,另一个就是下拉头的背景。

然后新建一个RefreshableView继承自LinearLayout,代码如下所示:

  1. package myview;
  2. import android.content.Context;
  3. import android.content.SharedPreferences;
  4. import android.os.AsyncTask;
  5. import android.preference.PreferenceManager;
  6. import android.util.AttributeSet;
  7. import android.view.LayoutInflater;
  8. import android.view.MotionEvent;
  9. import android.view.View;
  10. import android.view.ViewConfiguration;
  11. import android.view.animation.Animation;
  12. import android.view.animation.LinearInterpolator;
  13. import android.view.animation.RotateAnimation;
  14. import android.widget.ImageView;
  15. import android.widget.LinearLayout;
  16. import android.widget.ListView;
  17. import android.widget.ProgressBar;
  18. import android.widget.TextView;
  19. import com.yorhp.refreshview.R;
  20. import static android.R.attr.fromDegrees;
  21. import static android.R.attr.pivotX;
  22. import static android.R.attr.pivotY;
  23. import static android.R.attr.toDegrees;
  24. import static android.icu.lang.UCharacter.GraphemeClusterBreak.L;
  25. public class RefreshableViewList extends LinearLayout implements View.OnTouchListener {
  26. /**
  27. * 下拉状态
  28. */
  29. public static final int STATUS_PULL_TO_REFRESH = 0;
  30. /**
  31. * 释放立即刷新状态
  32. */
  33. public static final int STATUS_RELEASE_TO_REFRESH = 1;
  34. /**
  35. * 正在刷新状态
  36. */
  37. public static final int STATUS_REFRESHING = 2;
  38. /**
  39. * 刷新完成或未刷新状态
  40. */
  41. public static final int STATUS_REFRESH_FINISHED = 3;
  42. /**
  43. * 下拉头部回滚的速度
  44. */
  45. public static final int SCROLL_SPEED = -30;
  46. /**
  47. * 下拉的长度
  48. */
  49. private int pullLength;
  50. /**
  51. * 下拉刷新的回调接口
  52. */
  53. private PullToRefreshListener mListener;
  54. /**
  55. * 下拉头的View
  56. */
  57. private View header;
  58. /**
  59. * 需要去下拉刷新的ListView
  60. */
  61. private ListView listView;
  62. /**
  63. * 刷新时显示的进度条
  64. */
  65. // private ProgressBar progressBar;
  66. //三角形
  67. private ImageView iv_triangle;
  68. /**
  69. * 指示下拉和释放的箭头
  70. */
  71. // private ImageView arrow;
  72. /**
  73. * 指示下拉和释放的文字描述
  74. */
  75. //private TextView description;
  76. /**
  77. * 下拉头的布局参数
  78. */
  79. private MarginLayoutParams headerLayoutParams;
  80. /**
  81. * 为了防止不同界面的下拉刷新在上次更新时间上互相有冲突,使用id来做区分
  82. */
  83. private int mId = -1;
  84. /**
  85. * 下拉头的高度
  86. */
  87. private int hideHeaderHeight;
  88. /**
  89. * 当前处理什么状态,可选值有STATUS_PULL_TO_REFRESH, STATUS_RELEASE_TO_REFRESH,
  90. * STATUS_REFRESHING 和 STATUS_REFRESH_FINISHED
  91. */
  92. private int currentStatus = STATUS_REFRESH_FINISHED;
  93. ;
  94. /**
  95. * 记录上一次的状态是什么,避免进行重复操作
  96. */
  97. private int lastStatus = currentStatus;
  98. /**
  99. * 手指按下时的屏幕纵坐标
  100. */
  101. private float yDown;
  102. /**
  103. * 在被判定为滚动之前用户手指可以移动的最大值。
  104. */
  105. private int touchSlop;
  106. /**
  107. * 是否已加载过一次layout,这里onLayout中的初始化只需加载一次
  108. */
  109. private boolean loadOnce;
  110. /**
  111. * 当前是否可以下拉,只有ListView滚动到头的时候才允许下拉
  112. */
  113. private boolean ableToPull;
  114. /**
  115. * 下拉刷新控件的构造函数,会在运行时动态添加一个下拉头的布局。
  116. *
  117. * @param context
  118. * @param attrs
  119. */
  120. public RefreshableViewList(Context context, AttributeSet attrs) {
  121. super(context, attrs);
  122. header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh, null, true);
  123. iv_triangle = (ImageView) header.findViewById(R.id.iv_triangle);
  124. touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
  125. setOrientation(VERTICAL);
  126. addView(header, 0);
  127. }
  128. /**
  129. * 进行一些关键性的初始化操作,比如:将下拉头向上偏移进行隐藏,给ListView注册touch事件。
  130. */
  131. @Override
  132. protected void onLayout(boolean changed, int l, int t, int r, int b) {
  133. super.onLayout(changed, l, t, r, b);
  134. if (changed && !loadOnce) {
  135. hideHeaderHeight = -header.getHeight();
  136. pullLength = hideHeaderHeight / 4 * 3;
  137. headerLayoutParams = (MarginLayoutParams) header.getLayoutParams();
  138. headerLayoutParams.topMargin = hideHeaderHeight;
  139. listView = (ListView) getChildAt(1);
  140. listView.setOnTouchListener(this);
  141. loadOnce = true;
  142. }
  143. }
  144. int preDistance = 0;
  145. /**
  146. * 当ListView被触摸时调用,其中处理了各种下拉刷新的具体逻辑。
  147. */
  148. @Override
  149. public boolean onTouch(View v, MotionEvent event) {
  150. setIsAbleToPull(event);
  151. if (ableToPull) {
  152. switch (event.getAction()) {
  153. case MotionEvent.ACTION_DOWN:
  154. yDown = event.getRawY();
  155. break;
  156. case MotionEvent.ACTION_MOVE:
  157. float yMove = event.getRawY();
  158. int distance = (int) (yMove - yDown);
  159. // 如果手指是下滑状态,并且下拉头是完全隐藏的,就屏蔽下拉事件
  160. if (distance <= pullLength && headerLayoutParams.topMargin <= hideHeaderHeight) {
  161. return false;
  162. }
  163. if (distance < touchSlop) {
  164. return false;
  165. }
  166. if (currentStatus != STATUS_REFRESHING) {
  167. if (headerLayoutParams.topMargin > pullLength) {
  168. currentStatus = STATUS_RELEASE_TO_REFRESH;
  169. } else {
  170. currentStatus = STATUS_PULL_TO_REFRESH;
  171. }
  172. // 通过偏移下拉头的topMargin值,来实现下拉效果,修改分母可以有不同的拉力效果
  173. headerLayoutParams.topMargin = (int) ((distance / 2.8) + hideHeaderHeight);
  174. header.setLayoutParams(headerLayoutParams);
  175. //添加动画(这里是手指控制滑动的动画)、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
  176. rotateTriangle((distance - preDistance)/2);
  177. preDistance=distance;
  178. }
  179. break;
  180. case MotionEvent.ACTION_UP:
  181. default:
  182. if (currentStatus == STATUS_RELEASE_TO_REFRESH) {
  183. // 松手时如果是释放立即刷新状态,就去调用正在刷新的任务
  184. new RefreshingTask().execute();
  185. } else if (currentStatus == STATUS_PULL_TO_REFRESH) {
  186. // 松手时如果是下拉状态,就去调用隐藏下拉头的任务
  187. new HideHeaderTask().execute();
  188. }
  189. break;
  190. }
  191. // 时刻记得更新下拉头中的信息
  192. if (currentStatus == STATUS_PULL_TO_REFRESH
  193. || currentStatus == STATUS_RELEASE_TO_REFRESH) {
  194. updateHeaderView();
  195. // 当前正处于下拉或释放状态,要让ListView失去焦点,否则被点击的那一项会一直处于选中状态
  196. listView.setPressed(false);
  197. listView.setFocusable(false);
  198. listView.setFocusableInTouchMode(false);
  199. lastStatus = currentStatus;
  200. // 当前正处于下拉或释放状态,通过返回true屏蔽掉ListView的滚动事件
  201. return true;
  202. }
  203. }
  204. return false;
  205. }
  206. /**
  207. * 给下拉刷新控件注册一个监听器。
  208. *
  209. * @param listener 监听器的实现。
  210. * @param id 为了防止不同界面的下拉刷新在上次更新时间上互相有冲突, 请不同界面在注册下拉刷新监听器时一定要传入不同的id。
  211. */
  212. public void setOnRefreshListener(PullToRefreshListener listener, int id) {
  213. mListener = listener;
  214. mId = id;
  215. }
  216. /**
  217. * 当所有的刷新逻辑完成后,记录调用一下,否则你的ListView将一直处于正在刷新状态。
  218. */
  219. public void finishRefreshing() {
  220. currentStatus = STATUS_REFRESH_FINISHED;
  221. new HideHeaderTask().execute();
  222. }
  223. /**
  224. * 根据当前ListView的滚动状态来设定 {@link #ableToPull}
  225. * 的值,每次都需要在onTouch中第一个执行,这样可以判断出当前应该是滚动ListView,还是应该进行下拉。
  226. *
  227. * @param event
  228. */
  229. private void setIsAbleToPull(MotionEvent event) {
  230. View firstChild = listView.getChildAt(0);
  231. if (firstChild != null) {
  232. int firstVisiblePos = listView.getFirstVisiblePosition();
  233. if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
  234. if (!ableToPull) {
  235. yDown = event.getRawY();
  236. }
  237. // 如果首个元素的上边缘,距离父布局值为0,就说明ListView滚动到了最顶部,此时应该允许下拉刷新
  238. ableToPull = true;
  239. } else {
  240. if (headerLayoutParams.topMargin != hideHeaderHeight) {
  241. headerLayoutParams.topMargin = hideHeaderHeight;
  242. header.setLayoutParams(headerLayoutParams);
  243. }
  244. ableToPull = false;
  245. }
  246. } else {
  247. // 如果ListView中没有元素,也应该允许下拉刷新
  248. ableToPull = true;
  249. }
  250. }
  251. /**
  252. * 更新下拉头中的信息。
  253. */
  254. private void updateHeaderView() {
  255. if (lastStatus != currentStatus) {
  256. if (currentStatus == STATUS_PULL_TO_REFRESH) { //下拉状态
  257. } else if (currentStatus == STATUS_RELEASE_TO_REFRESH) { //释放状态
  258. } else if (currentStatus == STATUS_REFRESHING) { //刷新中
  259. iv_triangle.clearAnimation();
  260. TriangelRotate();
  261. }
  262. }
  263. }
  264. float preDegres = 0;
  265. //手指下拉的时候的动画
  266. private void rotateTriangle(float angle) {
  267. float pivotX = iv_triangle.getWidth() /2;
  268. float pivotY = (float) (iv_triangle.getHeight() /1.6);
  269. float fromDegrees = preDegres;
  270. float toDegrees = angle;
  271. RotateAnimation animation = new RotateAnimation(fromDegrees, toDegrees, pivotX, pivotY);
  272. animation.setDuration(10);
  273. animation.setFillAfter(true);
  274. iv_triangle.startAnimation(animation);
  275. preDegres = preDegres + angle;
  276. }
  277. //刷新的时候一直转的动画
  278. private void TriangelRotate(){
  279. float pivotX = iv_triangle.getWidth() /2;
  280. float pivotY = (float) (iv_triangle.getHeight() /1.6);
  281. RotateAnimation animation = new RotateAnimation(0f, 120f, pivotX, pivotY);
  282. animation.setDuration(50);
  283. animation.setRepeatMode(Animation.RESTART);
  284. animation.setRepeatCount(Animation.INFINITE);
  285. preDegres = 0;
  286. LinearInterpolator linearInterpolator=new LinearInterpolator();
  287. animation.setInterpolator(linearInterpolator);
  288. iv_triangle.startAnimation(animation);
  289. }
  290. /**
  291. * 正在刷新的任务,在此任务中会去回调注册进来的下拉刷新监听器。
  292. * 下拉超过了,要返回到刷新的位置
  293. *
  294. * @author guolin
  295. */
  296. class RefreshingTask extends AsyncTask<Void, Integer, Void> {
  297. @Override
  298. protected Void doInBackground(Void... params) {
  299. int topMargin = headerLayoutParams.topMargin;
  300. while (true) {
  301. topMargin = topMargin + SCROLL_SPEED;
  302. if (topMargin <= pullLength) {
  303. topMargin = pullLength;
  304. break;
  305. }
  306. publishProgress(topMargin);
  307. sleep(10);
  308. }
  309. currentStatus = STATUS_REFRESHING;
  310. publishProgress(pullLength);
  311. if (mListener != null) {
  312. mListener.onRefresh();
  313. }
  314. return null;
  315. }
  316. @Override
  317. protected void onProgressUpdate(Integer... topMargin) {
  318. updateHeaderView();
  319. headerLayoutParams.topMargin = topMargin[0];
  320. header.setLayoutParams(headerLayoutParams);
  321. //添加动画(这里是手指松开后返回到刷新位置的动画)、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
  322. }
  323. }
  324. /**
  325. * 隐藏下拉头的任务,当未进行下拉刷新或下拉刷新完成后,此任务将会使下拉头重新隐藏。
  326. *
  327. * @author guolin
  328. */
  329. class HideHeaderTask extends AsyncTask<Void, Integer, Integer> {
  330. @Override
  331. protected Integer doInBackground(Void... params) {
  332. int topMargin = headerLayoutParams.topMargin;
  333. while (true) {
  334. topMargin = topMargin + SCROLL_SPEED;
  335. if (topMargin <= hideHeaderHeight) {
  336. topMargin = hideHeaderHeight;
  337. break;
  338. }
  339. publishProgress(topMargin);
  340. sleep(10);
  341. }
  342. return topMargin;
  343. }
  344. @Override
  345. protected void onProgressUpdate(Integer... topMargin) {
  346. headerLayoutParams.topMargin = topMargin[0];
  347. header.setLayoutParams(headerLayoutParams);
  348. //添加动画(这里是手指松开后返回到初始位置的动画)、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
  349. }
  350. @Override
  351. protected void onPostExecute(Integer topMargin) {
  352. headerLayoutParams.topMargin = topMargin;
  353. header.setLayoutParams(headerLayoutParams);
  354. currentStatus = STATUS_REFRESH_FINISHED;
  355. //完成刷新、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
  356. iv_triangle.clearAnimation();
  357. }
  358. }
  359. /**
  360. * 使当前线程睡眠指定的毫秒数。
  361. *
  362. * @param time 指定当前线程睡眠多久,以毫秒为单位
  363. */
  364. private void sleep(int time) {
  365. try {
  366. Thread.sleep(time);
  367. } catch (InterruptedException e) {
  368. e.printStackTrace();
  369. }
  370. }
  371. /**
  372. * 下拉刷新的监听器,使用下拉刷新的地方应该注册此监听器来获取刷新回调。
  373. *
  374. * @author guolin
  375. */
  376. public interface PullToRefreshListener {
  377. /**
  378. * 刷新时会去回调此方法,在方法内编写具体的刷新逻辑。注意此方法是在子线程中调用的, 你可以不必另开线程来进行耗时操作。
  379. */
  380. void onRefresh();
  381. }
  382. }

代码说明

这个类是整个下拉刷新功能中最重要的一个类,注释已经写得比较详细了,我再简单解释一下。首先在RefreshableView的构造函数中动态添加了刚刚定义的pull_to_refresh这个布局作为下拉头,然后在onLayout方法中将下拉头向上偏移出了屏幕,再给ListView注册了touch事件。之后每当手指在ListView上滑动时,onTouch方法就会执行。在onTouch方法中的第一行就调用了setIsAbleToPull方法来判断ListView是否滚动到了最顶部,只有滚动到了最顶部才会执行后面的代码,否则就视为正常的ListView滚动,不做任何处理。当ListView滚动到了最顶部时,如果手指还在向下拖动,就会改变下拉头的偏移值,让下拉头显示出来,下拉的距离设定为手指移动距离的1/2.8,这样才会有拉力的感觉。如果下拉的距离足够大,在松手的时候就会执行刷新操作,如果距离不够大,就仅仅重新隐藏下拉头。

具体的刷新操作会在RefreshingTask中进行,其中在doInBackground方法中回调了PullToRefreshListener接口的onRefresh方法,这也是大家在使用RefreshableView时必须要去实现的一个接口,因为具体刷新的逻辑就应该写在onRefresh方法中,后面会演示使用的方法。

你可能一下子看起来觉得很多代码,但是如果你把自己实现的那些可以修改的代码删除后看起来就简单很多了。然后你再把自己的逻辑添加进去,你的代码可能别人看起来也很难的。最重要的是自己要亲手做,简单地看可能怎么也看不会。

下拉刷新那自然要适配RecyclerView和NestedScrollView,实现起来也很简单,就是在判定列表是否滑动到顶部的时候代码改动一下。

  1. //ListView判定方法
  2. private void setIsAbleToPull(MotionEvent event) {
  3. View firstChild = listView.getChildAt(0);
  4. if (firstChild != null) {
  5. int firstVisiblePos = listView.getFirstVisiblePosition();
  6. if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
  7. if (!ableToPull) {
  8. yDown = event.getRawY();
  9. }
  10. // 如果首个元素的上边缘,距离父布局值为0,就说明ListView滚动到了最顶部,此时应该允许下拉刷新
  11. ableToPull = true;
  12. } else {
  13. if (headerLayoutParams.topMargin != hideHeaderHeight) {
  14. headerLayoutParams.topMargin = hideHeaderHeight;
  15. header.setLayoutParams(headerLayoutParams);
  16. }
  17. ableToPull = false;
  18. }
  19. } else {
  20. // 如果ListView中没有元素,也应该允许下拉刷新
  21. ableToPull = true;
  22. }
  23. }
  24. //RecyclerView判定方法
  25. private void setIsAbleToPull(MotionEvent event) {
  26. View firstChild = listView.getChildAt(0);
  27. if (firstChild != null) {
  28. LinearLayoutManager lm = (LinearLayoutManager) listView.getLayoutManager();
  29. int firstVisiblePos = lm.findFirstVisibleItemPosition();
  30. if (firstVisiblePos == 0 && firstChild.getTop() == 0) {
  31. if (!ableToPull) {
  32. yDown = event.getRawY();
  33. }
  34. // 如果首个元素的上边缘,距离父布局值为0,就说明ListView滚动到了最顶部,此时应该允许下拉刷新
  35. ableToPull = true;
  36. } else {
  37. if (headerLayoutParams.topMargin != hideHeaderHeight) {
  38. headerLayoutParams.topMargin = hideHeaderHeight;
  39. header.setLayoutParams(headerLayoutParams);
  40. }
  41. ableToPull = false;
  42. }
  43. } else {
  44. // 如果ListView中没有元素,也应该允许下拉刷新
  45. ableToPull = true;
  46. }
  47. }
  48. //NestedScrollView
  49. private void setIsAbleToPull(MotionEvent event) {
  50. View firstChild = listView.getChildAt(0);
  51. if (firstChild != null) {
  52. int scrollY = listView.getScrollY();
  53. if (scrollY == 0 && firstChild.getTop() == 0) {
  54. if (!ableToPull) {
  55. yDown = event.getRawY();
  56. }
  57. // 如果首个元素的上边缘,距离父布局值为0,就说明ListView滚动到了最顶部,此时应该允许下拉刷新
  58. ableToPull = true;
  59. } else {
  60. if (headerLayoutParams.topMargin != hideHeaderHeight) {
  61. headerLayoutParams.topMargin = hideHeaderHeight;
  62. header.setLayoutParams(headerLayoutParams);
  63. }
  64. ableToPull = false;
  65. }
  66. } else {
  67. // 如果ListView中没有元素,也应该允许下拉刷新
  68. ableToPull = true;
  69. }
  70. }

添加动画和改变状态什么的重要的地方我注释出来了,自己去搞搞还是很有意思的。

参考文章:Android下拉刷新完全解析,教你如何一分钟实现下拉刷新功能

项目地址:Tyhj的可自定义下拉刷新控件

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注