实现效果:
图片素材:
--> 首先,写先下拉刷新时的刷新布局 pull_to_refresh.xml:
<resources> <string name="app_name">PullToRefreshTest</string> <string name="pull_to_refresh">下拉可以刷新</string> <string name="release_to_refresh">释放立即刷新</string> <string name="refreshing">正在刷新...</string> <string name="not_updated_yet">暂未更新过</string> <string name="updated_at">上次更新于%1$s前</string> <string name="updated_just_Now">刚刚更新</string> <string name="time_error">时间有问题</string></resources><?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" androID:ID="@+ID/pull_to_refresh_head" androID:layout_wIDth="match_parent" androID:layout_height="60dp"> <linearLayout androID:layout_wIDth="200dp" androID:layout_height="60dp" androID:layout_centerInParent="true" androID:orIEntation="horizontal"> <relativeLayout androID:layout_wIDth="0dp" androID:layout_height="60dp" androID:layout_weight="3"> <ImageVIEw androID:ID="@+ID/arrow" androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_centerInParent="true" androID:src="@mipmap/indicator_arrow" /> <Progressbar androID:ID="@+ID/progress_bar" androID:layout_wIDth="30dp" androID:layout_height="30dp" androID:layout_centerInParent="true" androID:visibility="gone" /> </relativeLayout> <linearLayout androID:layout_wIDth="0dp" androID:layout_height="60dp" androID:layout_weight="12" androID:orIEntation="vertical"> <TextVIEw androID:ID="@+ID/description" androID:layout_wIDth="match_parent" androID:layout_height="0dp" androID:layout_weight="1" androID:gravity="center_horizontal|bottom" androID:text="@string/pull_to_refresh" /> <TextVIEw androID:ID="@+ID/updated_at" androID:layout_wIDth="match_parent" androID:layout_height="0dp" androID:layout_weight="1" androID:gravity="center_horizontal|top" androID:text="@string/updated_at" /> </linearLayout> </linearLayout></relativeLayout>
stringspull_to_refresh--> 然后,也是主要的,自定义下拉刷新的 VIEw (包含下拉刷新所有 *** 作) RefreshVIEw.java:package com.dragon.androID.tofreshlayout;import androID.content.Context;import androID.content.SharedPreferences;import androID.os.AsyncTask;import androID.os.SystemClock;import androID.preference.PreferenceManager;import androID.util.AttributeSet;import androID.vIEw.LayoutInflater;import androID.vIEw.MotionEvent;import androID.vIEw.VIEw;import androID.vIEw.VIEwConfiguration;import androID.vIEw.animation.RotateAnimation;import androID.Widget.ImageVIEw;import androID.Widget.linearLayout;import androID.Widget.ListVIEw;import androID.Widget.Progressbar;import androID.Widget.TextVIEw;public class RefreshVIEw extends linearLayout implements VIEw.OntouchListener {private static final String TAG = RefreshVIEw.class.getSimplename();public enum PulL_STATUS {STATUS_PulL_TO_REFRESH(0),// 下拉状态STATUS_RELEASE_TO_REFRESH(1),// 释放立即刷新状态STATUS_REFRESHING(2),// 正在刷新状态STATUS_REFRESH_FINISHED(3); // 刷新完成或未刷新状态private int status; // 状态PulL_STATUS(int value) {this.status = value;}public int getValue() {return this.status;}}// 下拉头部回滚的速度public static final int SCRolL_SPEED = -20;// 一分钟的毫秒值,用于判断上次的更新时间public static final long ONE_MINUTE = 60 * 1000;// 一小时的毫秒值,用于判断上次的更新时间public static final long ONE_HOUR = 60 * ONE_MINUTE;// 一天的毫秒值,用于判断上次的更新时间public static final long ONE_DAY = 24 * ONE_HOUR;// 一月的毫秒值,用于判断上次的更新时间public static final long ONE_MONTH = 30 * ONE_DAY;// 一年的毫秒值,用于判断上次的更新时间public static final long ONE_YEAR = 12 * ONE_MONTH;// 上次更新时间的字符串常量,用于作为 SharedPreferences 的键值private static final String UPDATED_AT = "updated_at";// 下拉刷新的回调接口private PullToRefreshListener mListener;private SharedPreferences preferences; // 用于存储上次更新时间private VIEw header; // 下拉头的VIEwprivate ListVIEw ListVIEw; // 需要去下拉刷新的ListVIEwprivate Progressbar progressbar; // 刷新时显示的进度条private ImageVIEw arrow; // 指示下拉和释放的箭头private TextVIEw description; // 指示下拉和释放的文字描述private TextVIEw updateAt; // 上次更新时间的文字描述private marginLayoutParams headerLayoutParams; // 下拉头的布局参数private long lastUpdateTime; // 上次更新时间的毫秒值// 为了防止不同界面的下拉刷新在上次更新时间上互相有冲突,使用ID来做区分private int mID = -1;private int hIDeheaderHeight; // 下拉头的高度/*** 当前处理什么状态,可选值有 STATUS_PulL_TO_REFRESH,STATUS_RELEASE_TO_REFRESH,STATUS_REFRESHING 和 STATUS_REFRESH_FINISHED*/private PulL_STATUS currentStatus = PulL_STATUS.STATUS_REFRESH_FINISHED;// 记录上一次的状态是什么,避免进行重复 *** 作private PulL_STATUS lastStatus = currentStatus;private float yDown; // 手指按下时的屏幕纵坐标private int touchSlop; // 在被判定为滚动之前用户手指可以移动的最大值。private boolean loadOnce; // 是否已加载过一次layout,这里onLayout中的初始化只需加载一次private boolean abletoPull; // 当前是否可以下拉,只有ListVIEw滚动到头的时候才允许下拉/*** 下拉刷新控件的构造函数,会在运行时动态添加一个下拉头的布局*/public RefreshVIEw(Context context,AttributeSet attrs) {super(context,attrs);preferences = PreferenceManager.getDefaultSharedPreferences(context);header = LayoutInflater.from(context).inflate(R.layout.pull_to_refresh,null,true);progressbar = (Progressbar) header.findVIEwByID(R.ID.progress_bar);arrow = (ImageVIEw) header.findVIEwByID(R.ID.arrow);description = (TextVIEw) header.findVIEwByID(R.ID.description);updateAt = (TextVIEw) header.findVIEwByID(R.ID.updated_at);touchSlop = VIEwConfiguration.get(context).getScaledtouchSlop();refreshUpdatedAtValue();setorIEntation(VERTICAL);addVIEw(header,0);//Log.d(TAG,"RefreshVIEw Constructor() getChildAt(0): " + getChildAt(0));//Log.d(TAG,"RefreshVIEw Constructor() getChildAt(0): " + getChildAt(1));// ListVIEw = (ListVIEw) getChildAt(1);// ListVIEw.setontouchListener(this);}/*** 进行一些关键性的初始化 *** 作,比如:将下拉头向上偏移进行隐藏,给 ListVIEw 注册 touch 事件*/@OverrIDeprotected voID onLayout(boolean changed,int l,int t,int r,int b) {super.onLayout(changed,l,t,r,b);if (changed && !loadOnce) {hIDeheaderHeight = -header.getHeight();headerLayoutParams = (marginLayoutParams) header.getLayoutParams();headerLayoutParams.topmargin = hIDeheaderHeight;ListVIEw = (ListVIEw) getChildAt(1);//Log.d(TAG,"onLayout() getChildAt(0): " + getChildAt(0));//Log.d(TAG,"onLayout() ListVIEw: " + ListVIEw);ListVIEw.setontouchListener(this);loadOnce = true;}}/*** 当 ListVIEw 被触摸时调用,其中处理了各种下拉刷新的具体逻辑*/@OverrIDepublic boolean ontouch(VIEw v,MotionEvent event) {setCanAbletoPull(event); // 判断是否可以下拉if (abletoPull) {switch (event.getAction()) {case MotionEvent.ACTION_DOWN:yDown = event.getRawY();break;case MotionEvent.ACTION_MOVE:// 获取移动中的 Y 轴的位置float yMove = event.getRawY();// 获取从按下到移动过程中移动的距离int distance = (int) (yMove - yDown);// 如果手指是上滑状态,并且下拉头是完全隐藏的,就屏蔽下拉事件if (distance <= 0 && headerLayoutParams.topmargin <= hIDeheaderHeight) {return false;}if (distance < touchSlop) {return false;}// 判断是否已经在刷新状态if (currentStatus != PulL_STATUS.STATUS_REFRESHING) {// 判断设置的 topmargin 是否 > 0,默认初始设置为 -header.getHeight()if (headerLayoutParams.topmargin > 0) {currentStatus = PulL_STATUS.STATUS_RELEASE_TO_REFRESH;} else {// 否则状态为下拉中的状态currentStatus = PulL_STATUS.STATUS_PulL_TO_REFRESH;}// 通过偏移下拉头的 topmargin 值,来实现下拉效果headerLayoutParams.topmargin = (distance / 2) + hIDeheaderHeight;header.setLayoutParams(headerLayoutParams);}break;case MotionEvent.ACTION_UP:default:if (currentStatus == PulL_STATUS.STATUS_RELEASE_TO_REFRESH) {// 松手时如果是释放立即刷新状态,就去调用正在刷新的任务new RefreshingTask().execute();} else if (currentStatus == PulL_STATUS.STATUS_PulL_TO_REFRESH) {// 松手时如果是下拉状态,就去调用隐藏下拉头的任务new HIDeheaderTask().execute();}break;}// 时刻记得更新下拉头中的信息if (currentStatus == PulL_STATUS.STATUS_PulL_TO_REFRESH|| currentStatus == PulL_STATUS.STATUS_RELEASE_TO_REFRESH) {updateheaderVIEw();// 当前正处于下拉或释放状态,要让 ListVIEw 失去焦点,否则被点击的那一项会一直处于选中状态ListVIEw.setpressed(false);ListVIEw.setFocusable(false);ListVIEw.setFocusableIntouchMode(false);lastStatus = currentStatus;// 当前正处于下拉或释放状态,通过返回 true 屏蔽掉 ListVIEw 的滚动事件return true;}}return false;}/*** 给下拉刷新控件注册一个监听器** @param Listener 监听器的实现* @param ID 为了防止不同界面的下拉刷新在上次更新时间上互相有冲突,不同界面在注册下拉刷新监听器时一定要传入不同的 ID*/public voID setonRefreshListener(PullToRefreshListener Listener,int ID) {mListener = Listener;mID = ID;}/*** 当所有的刷新逻辑完成后,记录调用一下,否则你的 ListVIEw 将一直处于正在刷新状态*/public voID finishrefreshing() {currentStatus = PulL_STATUS.STATUS_REFRESH_FINISHED;preferences.edit().putLong(UPDATED_AT + mID,System.currentTimeMillis()).commit();new HIDeheaderTask().execute();}/*** 根据当前 ListVIEw 的滚动状态来设定 {@link #abletoPull}* 的值,每次都需要在 ontouch 中第一个执行,这样可以判断出当前应该是滚动 ListVIEw,还是应该进行下拉*/private voID setCanAbletoPull(MotionEvent event) {VIEw firstChild = ListVIEw.getChildAt(0);if (firstChild != null) {// 获取 ListVIEw 中第一个Item的位置int firstVisiblePos = ListVIEw.getFirstVisibleposition();// 判断第一个子控件的 top 是否和第一个 Item 位置相等if (firstVisiblePos == 0 && firstChild.gettop() == 0) {if (!abletoPull) {// getRawY() 获得的是相对屏幕 Y 方向的位置yDown = event.getRawY();}// 如果首个元素的上边缘,距离父布局值为 0,就说明 ListVIEw 滚动到了最顶部,此时应该允许下拉刷新abletoPull = true;} else {if (headerLayoutParams.topmargin != hIDeheaderHeight) {headerLayoutParams.topmargin = hIDeheaderHeight;header.setLayoutParams(headerLayoutParams);}abletoPull = false;}} else {// 如果 ListVIEw 中没有元素,也应该允许下拉刷新abletoPull = true;}}/*** 更新下拉头中的信息*/private voID updateheaderVIEw() {if (lastStatus != currentStatus) {if (currentStatus == PulL_STATUS.STATUS_PulL_TO_REFRESH) {description.setText(getResources().getString(R.string.pull_to_refresh));arrow.setVisibility(VIEw.VISIBLE);progressbar.setVisibility(VIEw.GONE);rotateArrow();} else if (currentStatus == PulL_STATUS.STATUS_RELEASE_TO_REFRESH) {description.setText(getResources().getString(R.string.release_to_refresh));arrow.setVisibility(VIEw.VISIBLE);progressbar.setVisibility(VIEw.GONE);rotateArrow();} else if (currentStatus == PulL_STATUS.STATUS_REFRESHING) {description.setText(getResources().getString(R.string.refreshing));progressbar.setVisibility(VIEw.VISIBLE);arrow.clearanimation();arrow.setVisibility(VIEw.GONE);}refreshUpdatedAtValue();}}/*** 根据当前的状态来旋转箭头*/private voID rotateArrow() {float pivotX = arrow.getWIDth() / 2f;float pivotY = arrow.getHeight() / 2f;float fromdegrees = 0f;float todegrees = 0f;if (currentStatus == PulL_STATUS.STATUS_PulL_TO_REFRESH) {fromdegrees = 180f;todegrees = 360f;} else if (currentStatus == PulL_STATUS.STATUS_RELEASE_TO_REFRESH) {fromdegrees = 0f;todegrees = 180f;}RotateAnimation animation = new RotateAnimation(fromdegrees,todegrees,pivotX,pivotY);animation.setDuration(100);animation.setFillAfter(true);arrow.startAnimation(animation);}/*** 刷新下拉头中上次更新时间的文字描述*/private voID refreshUpdatedAtValue() {lastUpdateTime = preferences.getLong(UPDATED_AT + mID,-1);long currentTime = System.currentTimeMillis();long timePassed = currentTime - lastUpdateTime;long timeIntoFormat;String updateAtValue;if (lastUpdateTime == -1) {updateAtValue = getResources().getString(R.string.not_updated_yet);} else if (timePassed < 0) {updateAtValue = getResources().getString(R.string.time_error);} else if (timePassed < ONE_MINUTE) {updateAtValue = getResources().getString(R.string.updated_just_Now);} else if (timePassed < ONE_HOUR) {timeIntoFormat = timePassed / ONE_MINUTE;String value = timeIntoFormat + "分钟";updateAtValue = String.format(getResources().getString(R.string.updated_at),value);} else if (timePassed < ONE_DAY) {timeIntoFormat = timePassed / ONE_HOUR;String value = timeIntoFormat + "小时";updateAtValue = String.format(getResources().getString(R.string.updated_at),value);} else if (timePassed < ONE_MONTH) {timeIntoFormat = timePassed / ONE_DAY;String value = timeIntoFormat + "天";updateAtValue = String.format(getResources().getString(R.string.updated_at),value);} else if (timePassed < ONE_YEAR) {timeIntoFormat = timePassed / ONE_MONTH;String value = timeIntoFormat + "个月";updateAtValue = String.format(getResources().getString(R.string.updated_at),value);} else {timeIntoFormat = timePassed / ONE_YEAR;String value = timeIntoFormat + "年";updateAtValue = String.format(getResources().getString(R.string.updated_at),value);}updateAt.setText(updateAtValue);}/*** 正在刷新的任务,在此任务中会去回调注册进来的下拉刷新监听器*/class RefreshingTask extends AsyncTask<VoID,Integer,VoID> {@OverrIDeprotected VoID doInBackground(VoID... params) {int topmargin = headerLayoutParams.topmargin;while (true) {topmargin = topmargin + SCRolL_SPEED;if (topmargin <= 0) {topmargin = 0;break;}publishProgress(topmargin);SystemClock.sleep(10);}currentStatus = PulL_STATUS.STATUS_REFRESHING;publishProgress(0);if (mListener != null) {mListener.onRefresh();}return null;}@OverrIDeprotected voID onProgressUpdate(Integer... topmargin) {updateheaderVIEw();headerLayoutParams.topmargin = topmargin[0];header.setLayoutParams(headerLayoutParams);}}/*** 隐藏下拉头的任务,当未进行下拉刷新或下拉刷新完成后,此任务将会使下拉头重新隐藏*/class HIDeheaderTask extends AsyncTask<VoID,Integer> {@OverrIDeprotected Integer doInBackground(VoID... params) {int topmargin = headerLayoutParams.topmargin;while (true) {topmargin = topmargin + SCRolL_SPEED;if (topmargin <= hIDeheaderHeight) {topmargin = hIDeheaderHeight;break;}publishProgress(topmargin);SystemClock.sleep(10);}return topmargin;}@OverrIDeprotected voID onProgressUpdate(Integer ... topmargin) {headerLayoutParams.topmargin = topmargin[0];header.setLayoutParams(headerLayoutParams);}@OverrIDeprotected voID onPostExecute(Integer topmargin) {headerLayoutParams.topmargin = topmargin;header.setLayoutParams(headerLayoutParams);currentStatus = PulL_STATUS.STATUS_REFRESH_FINISHED;}}/*** 下拉刷新的监听器,使用下拉刷新的地方应该注册此监听器来获取刷新回调*/public interface PullToRefreshListener {// 刷新时会去回调此方法,在方法内编写具体的刷新逻辑。注意此方法是在子线程中调用的, 可以不必另开线程来进行耗时 *** 作voID onRefresh();}}
--> 第三步,写主布局:
<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" tools:context=".MainActivity" > <com.dragon.androID.tofreshlayout.RefreshVIEw androID:ID="@+ID/refreshable_vIEw" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" > <ListVIEw androID:ID="@+ID/List_vIEw" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" > </ListVIEw> </com.dragon.androID.tofreshlayout.RefreshVIEw></relativeLayout>
--> 最后,Java 代码添加 ListVIEw 的数据:
package com.dragon.androID.tofreshlayout;import androID.os.Bundle;import androID.os.SystemClock;import androID.support.v7.app.AppCompatActivity;import androID.webkit.WebVIEw;import androID.Widget.ArrayAdapter;import androID.Widget.ListVIEw;public class MainActivity extends AppCompatActivity { RefreshVIEw refreshableVIEw; ListVIEw ListVIEw; ArrayAdapter<String> adapter; private WebVIEw webVIEw; private static int NUM = 30; String[] items = new String[NUM]; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); getSupportActionbar().hIDe(); for (int i = 0; i < items.length; i++) { items[i] = "列表项" + i; } refreshableVIEw = (RefreshVIEw) findVIEwByID(R.ID.refreshable_vIEw); ListVIEw = (ListVIEw) findVIEwByID(R.ID.List_vIEw); adapter = new ArrayAdapter<>(this,androID.R.layout.simple_List_item_1,items); ListVIEw.setAdapter(adapter); refreshableVIEw.setonRefreshListener(new RefreshVIEw.PullToRefreshListener() { @OverrIDe public voID onRefresh() { SystemClock.sleep(3000); refreshableVIEw.finishrefreshing(); } },0); }}
程序 Demo: 链接:http://pan.baIDu.com/s/1ge6Llw3 密码:skna
***************其实还应该再封装的...*****************
以上所述是小编给大家介绍的AndroID自定义控件下拉刷新实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程小技巧网站的支持!
总结以上是内存溢出为你收集整理的Android自定义控件下拉刷新实例代码全部内容,希望文章能够帮你解决Android自定义控件下拉刷新实例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)