Android控件ListView下拉刷新之SwipeRefreshLayout

Android开发过程中,因为UI展示效果比不上IOS,导致一大批平民控件战胜Google大神的尴尬局面。今天分享下Google自己的下拉刷新控件SwipeRefreshLayout。

照例,先上图片,不然浪费大家的时间。

Android控件ListView下拉刷新之SwipeRefreshLayout_第1张图片

Android控件ListView下拉刷新之SwipeRefreshLayout_第2张图片

各位效果看着如何?满意咱么就继续看看项目整体结构


然后上代码,先看资源文件

<span style="font-family:Comic Sans MS;font-size:24px;"><?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">下拉刷新数据</string>
    <string name="action_settings">Settings</string>

    <string name="pull_to_refresh">下拉刷新数据</string>
    <string name="release_to_refresh">释放刷新数据</string>
    <string name="refreshing">正在刷新……</string>
    <string name="not_refresh_before">暂未刷新过</string>
    <string name="last_modified_refresh">上次刷新时间:</string>
    <string name="refresh_just_now">刚刚刷新</string>
    <string name="refresh_time_error">刷新时间有问题</string>
</resources>
</span>

下面看展示页面文件

<span style="font-family:Comic Sans MS;font-size:24px;"><?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/ui_layout_top"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center"
        android:visibility="gone" >

        <ProgressBar
            android:id="@+id/ui_pro_refresh"
            android:layout_width="22dp"
            android:layout_height="22dp"
            android:layout_gravity="center"
            android:indeterminate="true"
            android:indeterminateBehavior="repeat"
            android:indeterminateDrawable="@drawable/loading_drawable" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/ui_text_desc"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal|bottom"
                android:text="@string/pull_to_refresh" />

            <TextView
                android:id="@+id/ui_text_timestamp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:gravity="center_horizontal|top" />
        </LinearLayout>
    </LinearLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/ui_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/ui_layout_top" >

        <ListView
            android:id="@+id/ui_list_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout></span>

最后看Java代码了,都有注释,哥们就不做解释了

<span style="font-family:Comic Sans MS;font-size:24px;">package com.android.francis.swiperefreshlayout;

import java.util.ArrayList;
import java.util.List;

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.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.francis.utils.DateUtils;
import com.android.francis.utils.L;
import com.android.francis.utils.SharedUtils;
import com.android.francis.utils.StringUtils;

/**
 * Android提供下拉刷新控件SwipeRefreshLayout
 * @author Francis-ChinaFeng
 * @version 1.0 2014-8-17
 */
public class MainActivity extends Activity {

	/** 将刷新时间存储在SharedPreferences中的标记  */
	public static final String LAST_MODIFIED_TIME = "last_modified_time";
	/** SharedPreferences操作帮助类 */
	private SharedUtils sharedUtils;
	/** 刷新操作提示Layout */
	private LinearLayout refreshTopLayout;
	/** 刷新操作提示TextView */
	private TextView descText, timestampText;

	/** Google官方提供的下拉刷新控件 */
	private SwipeRefreshLayout refreshLayout;
	private ListView listView;
	private List<String> list;
	private ArrayAdapter<String> adapter;

	/** other变量 */
	private String lastmodified, key;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
		setAdapter();
		setListener();
	}

	private void init() {
		sharedUtils = SharedUtils.getInstance(this);
		refreshTopLayout = (LinearLayout) findViewById(R.id.ui_layout_top);
		descText = (TextView) findViewById(R.id.ui_text_desc);
		timestampText = (TextView) findViewById(R.id.ui_text_timestamp);
		refreshLayout = (SwipeRefreshLayout) findViewById(R.id.ui_refresh_layout);
		listView = (ListView) findViewById(R.id.ui_list_view);
//		设置下拉刷新时颜色变化效果
		refreshLayout.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);
//		存储在SharedPreferences中的时间标记,一个项目中不可能只有一个ListView需要下拉刷新,所以添加类名称做区分
		key = LAST_MODIFIED_TIME + MainActivity.class.getName();
	}

	private void setAdapter() {
		list = new ArrayList<String>();
		list.add("A");
		list.add("B");
		list.add("C");
		list.add("D");
		list.add("E");
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
		listView.setAdapter(adapter);
	}

	private void setListener() {
//		添加ListView点击事件,测试是否存在某些Bug,感觉良好
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View v,
					int position, long id) {
				Toast.makeText(MainActivity.this, "xxxx", Toast.LENGTH_LONG)
						.show();
			}
		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				Toast.makeText(MainActivity.this, "yyyyy", Toast.LENGTH_LONG)
						.show();
				return false;
			}
		});
//		为refreshLayout添加下拉刷新操作事件监听
		refreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
//				此处判断下拉刷新提示Layout是否处于显示状态,以便于禁止重复刷新。
//				注:refreshLayout.isRefreshing();貌似有Bug,如果有解决该方法的小伙伴请告知
//				if (refreshLayout.isRefreshing()) {
				if (refreshTopLayout.getVisibility() == View.VISIBLE) {
					return;
				} else {
					lastmodified = DateUtils.dateToStr(System.currentTimeMillis());
					PullToRefreshAsyncTask task = new PullToRefreshAsyncTask();
					task.execute();
				}
			}
		});
	}

	/**
	 * 通过异步方法处理下拉刷新ListView的操作
	 * @author Francis-ChinaFeng
	 * @version 1.0 2014-8-17
	 */
	private class PullToRefreshAsyncTask extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			L.e(key);
			String timestamp = sharedUtils.getSharedString(key, "");
			refreshTopLayout.setVisibility(View.VISIBLE);
			descText.setText(R.string.refreshing);
			if (StringUtils.isNotEmpty(timestamp)) {
				timestampText.setText(R.string.last_modified_refresh);
				timestampText.append(timestamp);
			} else {
				timestampText.setText(R.string.not_refresh_before);
			}
		}

		@Override
		protected String doInBackground(Void... arg0) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			list.add("F");
			list.add("G");
			list.add("H");
			list.add("I");
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			adapter.notifyDataSetChanged();
			refreshTopLayout.setVisibility(View.GONE);
			sharedUtils.setSharedString(key, lastmodified);
//			取消刷新动画
			refreshLayout.setRefreshing(false);
		}
	}
}
</span>

估计对比平民控件,这里的效果代码太多了点,不过别担心,Google既然已经开始增加这些新控件,我想,大神们是要励志找回尊严的,Android加油!!

代码实现方面比较片面,如果大家知道系统已经提供了顶部提示信息,忘告知一二。

最后附上源码地址:http://download.csdn.net/detail/u011290399/7773229

你可能感兴趣的:(android,ListView,下拉刷新)