android谷歌官方自带SwipeRefreshLayout实现下拉刷新

来源:互联网 发布:青牛软件电话 编辑:程序博客网 时间:2024/05/23 23:47

效果图


代码

package com.xiaoke.freash;import java.util.ArrayList;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.support.v4.widget.SwipeRefreshLayout;import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;import android.widget.ArrayAdapter;import android.widget.ListView;public class MainActivity extends Activity {// 数据作为全局变量private ArrayList<String> list = null;private int index = 0;private ArrayAdapter adapter = null;private SwipeRefreshLayout swipere = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);list = new ArrayList<String>();// 通过布局文件获取下拉对象swipere = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);// 通过布局文件获取listview对象ListView lv = (ListView) findViewById(R.id.listView);// 下拉框的样式设计swipere.setColorSchemeResources(android.R.color.holo_blue_bright,android.R.color.holo_orange_light,android.R.color.holo_green_light);// 下拉监听事件swipere.setOnRefreshListener(new OnRefreshListener() {// 下拉或调用该方法@Overridepublic void onRefresh() {new MyTask().execute();}});// listview布局的样式adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,list);// 添加进listview中lv.setAdapter(adapter);}public class MyTask extends AsyncTask {@Overrideprotected void onPreExecute() {// true,刷新开始,所以启动刷新的UI样式.swipere.setRefreshing(true);}// 耗时操作@Overrideprotected Object doInBackground(Object... params) {try {// 开始启动刷新...// 在这儿放耗时操作的 AsyncTask线程、后台Service等代码。// add(0,xxx)每次将更新的数据xxx添加到头部。list.add(0, "" + index++);Thread.sleep(5000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}// 更新主线程@Overrideprotected void onPostExecute(Object result) {adapter.notifyDataSetChanged();// 刷新完毕.// false,刷新完成,因此停止UI的刷新表现样式。swipere.setRefreshing(false);}}}
布局代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <android.support.v4.widget.SwipeRefreshLayout        android:id="@+id/swipeRefreshLayout"        android:layout_width="match_parent"        android:layout_height="match_parent">        <ListView            android:id="@+id/listView"            android:layout_width="match_parent"            android:layout_height="match_parent" >        </ListView>    </android.support.v4.widget.SwipeRefreshLayout></LinearLayout>



0 0
原创粉丝点击