新建布局文件list_refresh.xml
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fram_list"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
//将布局文件和java文件绑定在一起
tools:context="com.example.doubandemo.ListRefresh"
>
<ListView
android:id="@+id/list_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</android.support.v4.widget.SwipeRefreshLayout>
新建ListRefreshFragment类继承Fragment类实现SwipeRefreshLayout.OnRefreshListener接口,重写onRefresh()方法
public void onRefresh() {
mSwipeRefreshLayout.setRefreshing(true);
new Handler().postDelayed(new Runnable() {
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
}
}, 3000);
}
然后在onCreateView()中加载布局
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//加载布局文件
View view = inflater.inflate(R.layout.list_refresh,container,false);
//初始化数据
initData();
mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.fram_list);
//为下拉刷新的滚动条设置颜色,可以设置4种
mSwipeRefreshLayout.setColorSchemeResources(
android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light
);
//因为实现了OnRefreshListener接口,所以这里可以传入this
mSwipeRefreshLayout.setOnRefreshListener(this);
ListView listView = (ListView) view.findViewById(R.id.list_item);
//填充ListView
listView.setAdapter(new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,listData));
return view;
}
在MainActivity中加载Fragment