在开发过程中,最常遇到的需求就是下拉刷新。刚开始时感觉下拉刷新挺难的,要么自定义控件,要么要去网上找轮子。其实在android-support-v4包中有一个控件SwipeRefreshLayout实现了下拉刷新的功能,而且只是一个ViewGroup,你想要那个控件具有下拉刷新的功能,只需要把这个控件放入这个布局中就行了,有没有很赞!让我们一起去看看如何使用它吧!
首先写出布局文件: activity_swipe.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/swipe_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.wind.test.activity.SwipeActivity">
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:text="下拉刷新" />
</android.support.v4.widget.SwipeRefreshLayout>
然后写出java文件: SwipeActivity.javapublic class
public class SwipeActivity extends AppCompatActivity {
private SwipeRefreshLayout swipeView;
private TextView content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe);
initViews();
}
private void initViews() {
content = (TextView) findViewById(R.id.content);
swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_view);
swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// 使用Handler模拟联网等延时操作
handler.postDelayed(loadRunnable, 3000);
}
});
}
private Handler handler = new Handler();
private final Runnable loadRunnable = new Runnable() {
int count = 0;
@Override
public void run() {
count++;
content.setText(String.format("这是第%d次刷新", count));
// 刷新结束隐藏刷新进度控件
swipeView.setRefreshing(false);
}
};
}
这样就可以愉快的下拉刷新了:
// 而且还可以用
SwipeRefreshLayout.setColorSchemeColors(@ColorInt int... colors)
// 或
SwipeRefreshLayout.setColorSchemeResources(@ColorRes int... colorResIds)
// 为圆形的进度控件设置颜色
快去找到项目合适的颜色吧。