首页 > 学院 > 开发设计 > 正文

给你的安卓app添加下拉刷新功能吧!

2019-11-08 00:36:21
字体:
来源:转载
供稿:网友

给Activity添加下拉刷新功能

有些时候,在开发app的时候,有一些特定场景需要用户手动刷新请求更新页面信息。例如,在开发一个新闻类软件的时候,我们可能会需要通过下拉刷新或者上拖加载去更新信息。这时候我们就可以借助组合ListView或GirdView和SwipeRefreshLayout去完成这一功能,该控件在Support-v4.jar中有,适合安卓1.6版本及以上。

实现功能的时候需要注意,SwipeRefreshLayout作为ListView或者GirdView的父组件,更新视图需要实现 SwipeRefreshLayout.OnRefreshListener接口,并实现其onRefresh方法,具体的更新内容建议在封装好的方法中,在onRefresh方法中直接调用,最后记得要用setRefreshing(false)将该指示器移除。 下面这个例子是我模拟下拉刷新的实现代码。 在这里我就简单的按照官网实现了这个功能,有兴趣的朋友可以参考一下这个链接安卓官网文档

SwipeRefreshActivity.java

public class SwipeRefreshActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener{ PRivate SwipeRefreshLayout swipeRefreshLayout; private RelativeLayout parent; //该处理器用来模拟延时回收刷新指示器 private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.arg1==0){ swipeRefreshLayout.setRefreshing(false); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_swipe_refresh); initView(); initEvent(); } private void initEvent() { swipeRefreshLayout.setOnRefreshListener(this); } private void initView() { swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh); parent = (RelativeLayout) findViewById(R.id.activity_swipe_refresh); } @Override public void onRefresh() { Log.i("LOG_TAG", "onRefresh called from SwipeRefreshLayout"); // This method performs the actual data-refresh Operation. // The method calls setRefreshing(false) when it's finished. myUpdateOperation(); } private void myUpdateOperation() { Snackbar.make(parent,"refreshing.......",Snackbar.LENGTH_SHORT).setAction("Action",null).show(); Message msg = new Message(); msg.arg1 = 0; mHandler.sendMessageDelayed(msg,2000); }}<?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:id="@+id/activity_swipe_refresh" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.yQQ.touchtest.Activity.SwipeRefreshActivity"> <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swiperefresh" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v4.widget.SwipeRefreshLayout></RelativeLayout>

下面内容还在创作中,请期待


上一篇:NSRange - 使用详解

下一篇:IPC机制

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表