以前我們做下拉刷新時沒有官方的,都是第三方自定義的控件,第三方雖然好用,但是時不時會蹦出個問題又很難解決,如今我們可以使用官方的進行數據刷新,布局只有一個listView,item布局只是一個TextView就不給出了,下面上效果圖
如上圖所示,這種官方的控件還有一個下拉的圓圈的樣式,就不給出了,下面介紹這個控件的使用,
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</android.support.v4.widget.SwipeRefreshLayout>
主布局就是一個刷新控件包裹一個listview
下面上代碼
public class MainActivity extends Activity implements SwipeRefreshLayout.OnRefreshListener {
private SwipeRefreshLayout swipeLayout;
private ListView listView;
private ListViewAdapter adapter;
private List<Entity> list;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(R.color.materialBlue,R.color.materialGreen,
R.color.materialRed, R.color.materialYellow);
list = new ArrayList<Entity>();
for (int i=0;i<4;i++){
list.add(new Entity("刷新"));
}
listView = (ListView) findViewById(R.id.list);
}
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
public void run() {
swipeLayout.setRefreshing(false);
list.add(new Entity("我們"));
adapter = new ListViewAdapter(MainActivity.this, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}, 100000);
}
}
接下來是adapter代碼
public class ListViewAdapter extends BaseAdapter {
private Context context;
private List<Entity> list;
public ListViewAdapter(Context context, List<Entity> list) {
this.context = context;
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int arg0) {
return null;
}
public long getItemId(int arg0) {
return 0;
}
public View getView(int position, View convertView, ViewGroup arg2) {
HolderView holderView = null;
if (convertView == null) {
holderView = new HolderView();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holderView.text = (TextView) convertView.findViewById(R.id.text);
} else {
convertView.getTag();
}
Entity entity=list.get(position);
holderView.text.setText(entity.getText()+"");
return convertView;
}
class HolderView {
TextView text;
}
}
以上就是全部代碼了,個人感覺挺好用的,最起碼穩定些,