SwipeRefreshLayout是android兼容包中的一个下拉刷新的控件,以前基本都使用XListView或者自己写一个下拉刷新。
下来简单介绍下SwipeRefreshLayout的使用:
1.布局文件:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.biyou.swiperefresh.MainActivity">
<android.support.v4.widget.SwipeRefreshLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/id_swipe">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/id_listview">
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
2.代码:
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
private ListView listView;
private SwipeRefreshLayout swipeRefreshLayout;
private ArrayAdapter<String> adapter;
private List<String> data = new ArrayList<String>(Arrays.asList("Android","Windows","Linux","Mac OS"));
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x10:
data.addAll(Arrays.asList("Symbian", "UNIX", "MS-DOS"));
adapter.notifyDataSetChanged();
swipeRefreshLayout.setRefreshing(false);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.id_listview);
swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.id_swipe);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setProgressBackgroundColorSchemeColor(Color.WHITE);
swipeRefreshLayout.setColorSchemeColors(Color.BLUE);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
}
@Override
public void onRefresh() {
//this is UI Thread
//do loading
//update UI
handler.sendEmptyMessageDelayed(0x10,1000);
}
}
实现SwipeRefreshLayout.OnRefreshListener接口,重写onRefresh()方法,在此方法中实现一些加载的逻辑。
setProgressBackgroundColorSchemeColor()方法设置加载Progress的背景颜色。
setColorSchemeColors()方法设置加载progress动画的颜色。
setRefreshing(false)方法停止动画效果。
效果如下: