您的位置:首页 > 其它

超简单!原生SwipeRefreshLayout实现首页下拉刷新

2016-12-19 17:03 393 查看

简介

SwipeRefreshLayout是Google官方推出的一款下拉刷新组件,位于v4兼容包下

android.support.v4.widget.SwipeRefreshLayout


这里简单介绍一下它的超简单的用法,因为我比较懒,所以直接上代码了!

布局

布局构造介绍

大概讲一下这个布局构造,直接从项目里贴过来的,主页用DragLayout布局的,由一个主页和一个侧边栏组成

xml

<android.support.v4.widget.SwipeRefreshLayoutandroid:id="@+id/main_refresh"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">

<!--Control-->
<com.jty.view.DragLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/dl"
android:layout_width="wrap_content"
android:layout_height="match_parent"
>

<!--侧滑-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#eff2f5"
>
</RelativeLayout>

<!--主页-->
<com.jty.view.MyRelativeLayout
android:id="@+id/activity_main"
android:background="@color/main_background"
android:layout_width="match_parent"
android:layout_height="match_parent">

</com.jty.view.MyRelativeLayout>

</com.jty.view.DragLayout>

</android.support.v4.widget.SwipeRefreshLayout>


实现逻辑

首先实现监听方法,并且设置监听

implements SwipeRefreshLayout.OnRefreshListener

/**
* Pull To ReFresh
*/
@BindView(R.id.main_refresh)
SwipeRefreshLayout mainRefresh;

private boolean isRefresh = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);

EventBus.getDefault().register(this);
//set refresh listener
mainRefresh.setOnRefreshListener(this);

isLogin();
}


然后进行写你自己的业务逻辑

重写onRefresh()方法:

/**
* Main Pull To Refresh
*/
@Override
public void onRefresh() {
//判断刷新状态
if (!isRefresh) {
isRefresh = true;
//send request
getInfo(username, token, ip);

}
}


在请求完成之后,发送一条请求到主线程:

//send msg to main
EventBus.getDefault().post("complete");


主线程处理

这里用的EventBus,可以当Handler用,主线程收到信息之后对状态进度条状态做处理,OK,完成了!

@Subscribe(threadMode = ThreadMode.MAIN)
public void MainHandler(String msg) {
if(msg.equals("complete")){
//完成请求后隐藏刷新进度条
mainRefresh.setRefreshing(false);
isRefresh = false;
}
}


后记

以上列出的只是SwipeRefreshLayout的一般用法,如果需要自定义的话就相对复杂一点了,可以参考Android官方说明:https://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html,真的特别详细!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: