Android 系统自带下拉刷新 SwipeRefreshLayout
jopen
9年前
-
创建 布局文件:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipe" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listview" android:footerDividersEnabled="false" android:headerDividersEnabled="false" android:background="@android:color/darker_gray" /> </android.support.v4.widget.SwipeRefreshLayout>
此处 标签 一定要写 全称:
android.support.v4.widget.SwipeRefreshLayout
否则 会出现 以下异常:
11-25 21:23:15.819 31408-31408/com.example.leonardo.bmobtest E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.leonardo.bmobtest/com.example.leonardo.bmobtest.SwipeRefreshActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class SwipeRefreshLayout
2. 在 Activity中使用:
.setColorSchemeResources(android.R.color.,android.R.color.,android.R.color.,android.R.color.);
3.设置 onRefresh 侦听器:
.setOnRefreshListener(SwipeRefreshLayout.OnRefreshListener() { onRefresh() { Handler().postDelayed(Runnable() { run() { .add(,+ Random()); .notifyDataSetChanged(); .setRefreshing(); } }, ); } });
即可实现,简单 漂亮的 下拉刷新效果,以下为 Activity 全部代码:
package com.example.leonardo.bmobtest; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.SwipeRefreshLayout; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import java.util.Random; import roboguice.activity.RoboActivity; import roboguice.inject.InjectView; /** * Created by leonardo on 15/11/25. */ public class SwipeRefreshActivity extends RoboActivity{ @InjectView(R.id.swipe) SwipeRefreshLayout swipeRefreshLayout; @InjectView(R.id.listview) ListView listView; List<String> datas; ArrayAdapter<String> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_swipe); datas = new ArrayList<>(); for (int i=0;i<10;i++){ datas.add("item "+i); } adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,datas); adapter.notifyDataSetChanged(); listView.setAdapter(adapter); swipeRefreshLayout.setColorSchemeResources(android.R.color.black,android.R.color.holo_orange_dark,android.R.color.holo_red_dark,android.R.color.holo_green_dark); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { datas.add(0,"item new" + new Random(10)); adapter.notifyDataSetChanged(); swipeRefreshLayout.setRefreshing(false); } }, 4000); } }); } }
此处使用的是 roboguice 依赖库