Android開源項目pulltorefresh分析與簡單使用

來源:互聯網
上載者:User

標籤:listview   refresh   

在Android開發中有時我們需要訪問網路即時重新整理資料,比如QQ好友線上狀態最新資訊,QQ空間需要顯示更多的社交動向更新資訊,EOE論壇用戶端顯示更多的文章文章資訊等。android-pulltorefresh開源項目提供一個向下滑動即重新整理列表的功能,將該項目稍作修改即可應用到自己的項目中。


1.

https://github.com/johannilsson/android-pulltorefresh

該項目為 Android 應用提供一個向下滑動即重新整理列表的功能。


2.工程組成

PullToRefreshListView.java

OnRefreshListener 監聽重新整理操作的介面 ,onRefresh()重新整理函數 在列表頭部顯示進行中的重新整理操作進度條

onRefreshComplete() 重新整理操作完成後,恢複列表常態

上述類和介面的具體實現:

public class PullToRefreshListView extends ListView implements OnScrollListener{  /**Interface definition for a callback to be invoked when list should be refreshed.     */    public interface OnRefreshListener {        /**         * Called when the list should be refreshed.         * <p>         * A call to {@link PullToRefreshListView #onRefreshComplete()} is expected to indicate that the refresh has completed.         */        public void onRefresh();    }/**     * Resets the list to a normal state after a refresh.     * @param lastUpdated Last updated at.     */    public void onRefreshComplete(CharSequence lastUpdated) {        setLastUpdated(lastUpdated);        onRefreshComplete();    }    /**     * Resets the list to a normal state after a refresh.     */    public void onRefreshComplete() {                Log.d(TAG, "onRefreshComplete");        resetHeader();// If refresh view is visible when loading completes, scroll down to// the next item.        if (getFirstVisiblePosition() == 0) {            invalidateViews();            setSelection(1);        }    }}

pull_to_refresh_header.xml

PullToRefreshListView頭部 顯示重新整理進度條資訊 ,在 PullToRefreshListView.java調用下面的語句將該子布局添加到列表頂部

private LayoutInflater mInflater;

private RelativeLayout mRefreshView;

 mInflater = (LayoutInflater) context.getSystemService(
                Context.LAYOUT_INFLATER_SERVICE);
//header part of PullToRefreshListView
mRefreshView = (RelativeLayout) mInflater.inflate(R.layout.pull_to_refresh_header, this, false);

 //add header part to the ListView
addHeaderView(mRefreshView);

PullToRefreshActivity.java   (MainActivity)

pull_to_refresh.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    >    <!--    The PullToRefreshListView replaces a standard ListView widget.    -->    <com.markupartist.android.widget.PullToRefreshListView        android:id="@+id/android:list"        android:layout_height="fill_parent"        android:layout_width="fill_parent"        /></LinearLayout>
註:

LiveActivity本身繼承了關於List操作的眾多介面,我們可以方便的重寫這些操作中需要的方法來實現自己需要的功能。如果要用ListActivity,則 Activity的Layout檔案中必須包括一個(只能一個)ListView,且ListView的id= "@id/android:list"。


3.PullToRefreshActivity.java

重新整理額外的列表資料String mExtras[],當額外列表資料顯示完畢時,不再進行重新整理操作。

例如下面這個例子重新整理三次以後,就沒有額外需要顯示的資料,拉松列表進行重新整理操作將提示“No More Messages”

package com.markupartist.android.example.pulltorefresh;import java.util.Arrays;import java.util.LinkedList;import android.annotation.SuppressLint;import android.app.ListActivity;import android.os.AsyncTask;import android.os.Bundle;import android.widget.ArrayAdapter;import android.widget.Toast;import com.markupartist.android.widget.PullToRefreshListView;import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener;@SuppressLint("NewApi")public class PullToRefreshActivity extends ListActivity {        private LinkedList<String> mListItems;    int count = 0;        /** Called when the activity is first created. */    @SuppressLint("NewApi")@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.pull_to_refresh);                // Set a listener to be invoked when the list should be refreshed.        ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {            @Override            public void onRefresh() {                // Do work to refresh the list here.            if(count < mExtras.length)            new GetDataTask().execute(count++);            else{            Toast.makeText(getApplicationContext(), "No More Messages",             Toast.LENGTH_LONG).show();                        //Resets the list to a normal state after a refresh            ((PullToRefreshListView) getListView()).onRefreshComplete();            }                        }        });        mListItems = new LinkedList<String>();        mListItems.addAll(Arrays.asList(mStrings));        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,                android.R.layout.simple_list_item_1, mListItems);        setListAdapter(adapter);    }    private class GetDataTask extends AsyncTask<Integer, Void, String[]> {        private int count;            @Override        protected String[] doInBackground(Integer... params) {        count = params[0];        // Simulates a background job.            try {                Thread.sleep(2000);            } catch (InterruptedException e) {                ;            }            return mStrings;        }        @SuppressLint("NewApi")@Override        protected void onPostExecute(String[] result) {           // mListItems.addFirst("Added after refresh...");        mListItems.addFirst(mExtras[count]);            // Call onRefreshComplete when the list has been refreshed.            ((PullToRefreshListView) getListView()).onRefreshComplete();           // super.onPostExecute(result);        }    }    private String[] mStrings = {            "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam",            "Abondance", "Ackawi", "Acorn", "Adelost", "Affidelice au Chablis",            "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",            "Allgauer Emmentaler"};        private String[] mExtras = {"extra1","extra2","extra3"};    }



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.