PullToRefresh實現下拉刷新上拉加載

最近學習了一款上拉刷新下拉加載的第三方庫,挺好用的,順便也學習下寫博客,寫的很差還請勿噴!java

PullToRefresh第三方庫的下載地址:(https://github.com/chrisbanes/Android-PullToRefresh)android

下載好後做爲一個library導入到studio的項目中,導入的時候可能會報錯,本身解決下gradle的版本問題git

首先佈局:github

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="android.shuaxin.MainActivity">

    <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="2dp"
        android:fadingEdge="none"
        android:fastScrollEnabled="false"
        android:footerDividersEnabled="false"
        android:headerDividersEnabled="false"
        android:smoothScrollbar="true" />
</RelativeLayout>

 

 

而後在代碼中進行實例化和配置異步

 

 

 

public final class MainActivity extends ListActivity {



    private LinkedList<String> mListItems;
    private PullToRefreshListView mPullRefreshListView;
    private ArrayAdapter<String> mAdapter;
    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" };

    /** Called when the activity is first created. */ @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        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);

                // Update the LastUpdatedLabel
                //設置更新時間
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);

                // Do work to refresh the list here.
                new GetDataTask().execute();
            }
        });

        //設置監聽最後一條
        mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
                Toast.makeText(MainActivity.this, "滑動到最後一條了!", Toast.LENGTH_SHORT).show();
            }
        });

        //獲得ListView
        ListView actualListView = 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);

        // You can also just use setListAdapter(mAdapter) or
        // mPullRefreshListView.setAdapter(mAdapter)
        actualListView.setAdapter(mAdapter);
            mPullRefreshListView.setMode(Mode.BOTH);//設置能夠同時上拉刷新和下拉加載
        //此處更改後onPostExecute方法也須要更改下內容,刪除if條件語句
//            mPullRefreshListView.setMode(Mode.PULL_FROM_START);//設置只能夠下拉
//            mPullRefreshListView.setMode(Mode.PULL_FROM_END);//設置只能夠上拉

    }


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

        @Override
        protected String[] doInBackground(Void... params) {
            // 異步加載線程休眠1.5秒
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
            }
            return mStrings;
        }

        @Override
        protected void onPostExecute(String[] result) {
            if (mPullRefreshListView.isHeaderShown()){
                mListItems.addFirst("下拉刷新到新數據");
            }else if (mPullRefreshListView.isFooterShown()){
                mListItems.addLast("上拉加載到新數據");
            }

            mAdapter.notifyDataSetChanged();
            // Call onRefreshComplete when the list has been refreshed.
            mPullRefreshListView.onRefreshComplete();

            super.onPostExecute(result);
        }
    }





}

 

 

 

在onPostExecute方法中的isHeaderShown()和isFooterShown()是本身在庫中添加的接口,在library\src\main\Java\com\handmark\pulltorefresh\library\PullToRefreshAdapterViewBase類下添加兩個接口用來判區分是上拉仍是下拉:ide

 

public boolean isHeaderShown() {
   return getHeaderLayout().isShown();
}

public boolean isFooterShown() {
   return getFooterLayout().isShown();
}

此時運行程序已經能夠達到上拉加載下拉刷新的效果了,可是不管是上拉仍是下拉所彈出的刷新界面此時都是下拉刷新字樣,那麼如何更改呢?佈局

 

 

 

在library\src\main\java\com\handmark\pulltorefresh\library\internal\LoadingLayout類下更改mPullLabel的值,個人是在在第95行,將值改成上拉刷新便可學習

 

 

到此爲止大功告成!gradle

 

 

項目地址:http://download.csdn.NET/detail/zhangzibin1992/9756718this

相關文章
相關標籤/搜索