天天看點

Android-PullToRefresh的簡單使用

一、PullToRefresh簡介

1.PullToRefresh介紹

        PullToRefresh是一套實作非常好的下拉重新整理庫,它支援:

        ListView

        ExpandableListView

        GridView

        WebView

        ScrollView

        HorizontalScrollView

        ViewPager

        等多種常用的需要重新整理的View類型,而且使用起來也十分友善。

2.PullToRefresh項目位址

        https://github.com/chrisbanes/Android-PullToRefresh

3.

4.

5.

6.

7.

二、PullToRefresh使用

1.ListView中使用PullToRefreshListView

1)布局代碼

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <include layout="@layout/titlebar"></include>


    <com.handmark.pulltorefresh.library.PullToRefreshListView
        android:id="@+id/pull_refresh_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:cacheColorHint="#00000000"
        android:divider="#19000000"
        android:dividerHeight="4dp"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:smoothScrollbar="true" />

</LinearLayout>
           

2)Activity代碼

public  class PullToRefreshListActivity extends ListActivity {


    private LinkedList<String> mListItems;
    private PullToRefreshListView mPullRefreshListView;
    private ArrayAdapter<String> mAdapter;
    private TextView tv_title;

    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", "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"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptr_list);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("PullToRefreshListView");

        mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);

        // Set a listener to be invoked when the list should be refreshed.
        mPullRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {

                // 添加重新整理時間
                String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                // 請求資料
                new GetDataTask().execute();
            }
        });

        // 監聽ListView最後一條
        mPullRefreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
//        Toast.makeText(PullToRefreshListActivity.this, "監listView的最後一條item", Toast.LENGTH_SHORT).show();
                mPullRefreshListView.setMode(PULL_FROM_END);
            }
        });


        ListView listview = mPullRefreshListView.getRefreshableView();


        mListItems = new LinkedList<String>();
        mListItems.addAll(Arrays.asList(mStrings));

        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
        /**
         *
         * Add Sound Event Listener 添加事件監聽聲音
         */
        SoundPullEventListener<ListView> soundListener = new SoundPullEventListener<ListView>(this);
        soundListener.addSoundEvent(State.PULL_TO_REFRESH, R.raw.pull_event);
        soundListener.addSoundEvent(State.RESET, R.raw.reset_sound);
        soundListener.addSoundEvent(State.REFRESHING, R.raw.refreshing_sound);
        mPullRefreshListView.setOnPullEventListener(soundListener);

        // 設定擴充卡
        listview.setAdapter(mAdapter);

        mPullRefreshListView.setMode(PULL_FROM_START);
    }
        
    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            return mStrings;
        }

        @Override
        protected void onPostExecute(String[] result) {
            if (mPullRefreshListView.getMode() == PULL_FROM_START) {
                mListItems.addFirst("Added after refresh...");
            } else if (mPullRefreshListView.getMode() == PULL_FROM_END) {
                mListItems.addLast("Added PULL_FROM_END refresh...");
            }

            mAdapter.notifyDataSetChanged();
            mPullRefreshListView.onRefreshComplete();

            super.onPostExecute(result);
        }
    }


}

           

2.GridView中使用PullToRefreshListView

   1)布局代碼

<?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" >

    <include layout="@layout/titlebar"></include>

<!-- The PullToRefreshGridView replaces a standard GridView widget. -->
    <com.handmark.pulltorefresh.library.PullToRefreshGridView
        xmlns:ptr="http://schemas.android.com/apk/res-auto"
        android:id="@+id/pull_refresh_grid"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:numColumns="auto_fit"
        android:verticalSpacing="1dp"
        android:horizontalSpacing="1dp"
        android:columnWidth="100dp"
        android:stretchMode="columnWidth"
        android:gravity="fill"
        ptr:ptrMode="both"
        />

</LinearLayout>
           

    2)Activity 代碼

public class PullToRefreshGridActivity extends Activity {


    private LinkedList<String> mListItems;
    private PullToRefreshGridView mPullRefreshGridView;
    private GridView mGridView;
    private ArrayAdapter<String> mAdapter;
    private TextView tv_title;

    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"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptr_grid);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("PullToRefreshGridView");

        mPullRefreshGridView = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid);
        mGridView = mPullRefreshGridView.getRefreshableView();

        // 設定上拉和下拉重新整理
        mPullRefreshGridView.setOnRefreshListener(new OnRefreshListener2<GridView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                Toast.makeText(PullToRefreshGridActivity.this, "下拉重新整理", Toast.LENGTH_SHORT).show();
                new GetDataTask().execute();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                Toast.makeText(PullToRefreshGridActivity.this, "上拉重新整理", Toast.LENGTH_SHORT).show();
                new GetDataTask().execute();
            }

        });

        mListItems = new LinkedList<String>();

        TextView tv = new TextView(this);
        tv.setGravity(Gravity.CENTER);
        tv.setText("目前沒有内容,請上下重新整理");
        mPullRefreshGridView.setEmptyView(tv);

        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mListItems);
        mGridView.setAdapter(mAdapter);
    }

    private class GetDataTask extends AsyncTask<Void, Void, String[]> {

        @Override
        protected String[] doInBackground(Void... params) {
            // Simulates a background job.
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            return mStrings;
        }

        @Override
        protected void onPostExecute(String[] result) {
            mListItems.addFirst("Added after refresh...");
            mListItems.addAll(Arrays.asList(result));
            mAdapter.notifyDataSetChanged();
            // Call onRefreshComplete when the list has been refreshed.
            mPullRefreshGridView.onRefreshComplete();

            // 添加重新整理時間
            String label = DateUtils.formatDateTime(getApplicationContext(), System.currentTimeMillis(),
                    DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
            mPullRefreshGridView.getLoadingLayoutProxy().setLastUpdatedLabel(label);


            super.onPostExecute(result);
        }
    }


}

           

三、謝謝浏覽!