AndroidオープンソースプロジェクトPull Torefreshドロップリフレッシュ機能詳細


まず効果図を見ます。

オープンソースアドレス:https://github.com/chrisbanes/Android-PullToRefresh 
この機能を更新します。私たちはよく見られます。今日紹介したのはこの機能の実現です。このオープンソースの例を紹介します。今日は一般的なPull Torefsh ListViewを紹介します。listViewにドロップダウンリフレッシュ機能があるようにします。 
1.プロジェクトバッグをダウンロードして、libraryバッグを導入すればいいです。他のカバンはしばらく使わないです。
2.ソースを分析して、設定できるのはどれですか? 

<?xml version="1.0" encoding="utf-8"?>
<resources>

 <declare-styleable name="PullToRefresh">

 <!-- A drawable to use as the background of the Refreshable View -->
 <!--     view    -->
 <attr name="ptrRefreshableViewBackground" format="reference|color" />

 <!-- A drawable to use as the background of the Header and Footer Loading Views -->
 <!--     view    -->
 <attr name="ptrHeaderBackground" format="reference|color" />

 <!-- Text Color of the Header and Footer Loading Views -->
 <!--     /        -->
 <attr name="ptrHeaderTextColor" format="reference|color" />

 <!-- Text Color of the Header and Footer Loading Views Sub Header -->
 <!--     /           -->
 <attr name="ptrHeaderSubTextColor" format="reference|color" />

 <!-- Mode of Pull-to-Refresh that should be used -->
 <!--          ,       。     ,     ,     ,    ,        -->
 <attr name="ptrMode">
  <flag name="disabled" value="0x0" />
  <flag name="pullFromStart" value="0x1" />
  <flag name="pullFromEnd" value="0x2" />
  <flag name="both" value="0x3" />
  <flag name="manualOnly" value="0x4" />

  <!-- These last two are depreacted -->
  <!--          ,         -->
  <flag name="pullDownFromTop" value="0x1" />
  <flag name="pullUpFromBottom" value="0x2" />
 </attr>

 <!-- Whether the Indicator overlay(s) should be used -->
 <!--          -->
 <attr name="ptrShowIndicator" format="reference|boolean" />

 <!-- Drawable to use as Loading Indicator. Changes both Header and Footer. -->
 <!--         -->
 <attr name="ptrDrawable" format="reference" />

 <!-- Drawable to use as Loading Indicator in the Header View. Overrides value set in ptrDrawable. -->
 <!--          ,      ptrDrawable       -->
 <attr name="ptrDrawableStart" format="reference" />

 <!-- Drawable to use as Loading Indicator in the Fooer View. Overrides value set in ptrDrawable. -->
 <!--          ,      ptrDrawable       -->
 <attr name="ptrDrawableEnd" format="reference" />

 <!-- Whether Android's built-in Over Scroll should be utilised for Pull-to-Refresh. -->
 <attr name="ptrOverScroll" format="reference|boolean" />

 <!-- Base text color, typeface, size, and style for Header and Footer Loading Views -->
 <!--           -->
 <attr name="ptrHeaderTextAppearance" format="reference" />

 <!-- Base text color, typeface, size, and style for Header and Footer Loading Views Sub Header -->
 <!--            -->
 <attr name="ptrSubHeaderTextAppearance" format="reference" />

 <!-- Style of Animation should be used displayed when pulling. -->
 <!--            ,   rotate -->
 <attr name="ptrAnimationStyle">
  <flag name="rotate" value="0x0" />
  <flag name="flip" value="0x1" />
 </attr>

 <!-- Whether the user can scroll while the View is Refreshing -->
 <!--            ,   true -->
 <attr name="ptrScrollingWhileRefreshingEnabled" format="reference|boolean" />

 <!--
  Whether PullToRefreshListView has it's extras enabled. This allows the user to be 
  able to scroll while refreshing, and behaves better. It acheives this by adding
  Header and/or Footer Views to the ListView.
 -->
 <!--    listview    /    -->
 <attr name="ptrListViewExtrasEnabled" format="reference|boolean" />

 <!--
  Whether the Drawable should be continually rotated as you pull. This only
  takes effect when using the 'Rotate' Animation Style.
 -->
 <!--    rotate ,                 -->
 <attr name="ptrRotateDrawableWhilePulling" format="reference|boolean" />

 <!-- BELOW HERE ARE DEPRECEATED. DO NOT USE. -->
 <attr name="ptrAdapterViewBackground" format="reference|color" />
 <attr name="ptrDrawableTop" format="reference" />
 <attr name="ptrDrawableBottom" format="reference" />
 </declare-styleable>

</resources>

これだけ設定できる属性があるので、本当にカスタマイズできるとは思わないでください。本当にカスタマイズしたいです。また、layoutで更新レイアウトを変更します。 

3.それを使って自分のプロジェクトを作り始めます。
 レイアウトファイルの設定
 Pull Torefresh ListViewを挿入します。

<RelativeLayout 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"
 tools:context="${relativePackage}.${activityClass}" 
 android:background="#000000">

<!-- The PullToRefreshListView replaces a standard ListView widget. -->

 <com.handmark.pulltorefresh.library.PullToRefreshListView
 xmlns:ptr="http://schemas.android.com/apk/res-auto"
 android:id="@+id/pull_refresh_list"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:cacheColorHint="#000000"
 android:divider="#19000000"
 android:dividerHeight="4dp"
 android:fadingEdge="none"
 android:fastScrollEnabled="false"
 android:footerDividersEnabled="false"
 android:headerDividersEnabled="false"
 android:smoothScrollbar="true" 
 ptr:ptrAnimationStyle="rotate"
 ptr:ptrHeaderTextColor="#ffffff"
 ptr:ptrHeaderSubTextColor="#00ffff"
 ptr:ptrHeaderBackground="@null"
 ptr:ptrDrawable="@drawable/ic_launcher"/>
 
</RelativeLayout>

コードの作成を開始 
1.このコントロールを見つけ、モニターを設定する 
この中には日付を使ったツール類がありますが、実は前回のドロップダウンの時間を設定しました。また、ドロップダウン後に非同期タスクをトリガします。 

 /**
 *        listview   
 */
 private void initPTRListView() {
 mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
 //       
 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);

  //      label
  refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
  //         ,            
  new GetDataTask(mPullRefreshListView, mAdapter,mListItems).execute();
  }
 });

 //            
 mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
  
  @Override
  public void onLastItemVisible() {
  Toast.makeText(getApplication(), "     ", Toast.LENGTH_SHORT).show();
  }
 });
 
 //mPullRefreshListView.isScrollingWhileRefreshingEnabled();//          
 //          
 mPullRefreshListView.setScrollingWhileRefreshingEnabled(true);
 //mPullRefreshListView.getMode();//    
 //          。       :Mode.PULL_FROM_START,Mode.BOTH,PULL_FROM_END
 mPullRefreshListView.setMode(Mode.BOTH);
 
 /**
  *       
  */
 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);
 }

2.上のコントロールからlistViewを取得し、アダプターを設置する。 

 //   listview  
 private ListView actualListView;
 //        ,   string  ,         string       
 private LinkedList<String> mListItems;
 // listview          
 private ArrayAdapter<String> mAdapter;

ここではLinked Listのオブジェクトを使用しています。これはArayListのようなチェーン配列で、先頭と最後にSteringを追加するのに便利です。 

 /**
 *   listview    
 */
 private void initListView() {
 //  getRefreshableView()     listview  
 actualListView = mPullRefreshListView.getRefreshableView();
 
 String []data = new String[] {"android","ios","wp","java","c++","c#"};
 mListItems = new LinkedList<String>();
 // string    string      
 mListItems.addAll(Arrays.asList(data));
 
 mAdapter = new ArrayAdapter<>(getApplicationContext(), 
  android.R.layout.simple_list_item_1, mListItems);
 actualListView.setAdapter(mAdapter);
 }

 
3.非同期のタスクを書いて、ネットワークからデータをロードすることを真似します。
ここで注意したいのは、ローディングが完了したらリフレッシュ完了とアダプターの変更を通知する方法です。

package com.kale.ptrlistviewtest;

import java.util.LinkedList;

import android.os.AsyncTask;
import android.widget.ArrayAdapter;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;

/**
 * @author:Jack Tony
 * @tips :               ,    
 * @date :2014-10-14
 */
public class GetDataTask extends AsyncTask<Void, Void, Void>{

 private PullToRefreshListView mPullRefreshListView;
 private ArrayAdapter<String> mAdapter;
 private LinkedList<String> mListItems;
 
 public GetDataTask(PullToRefreshListView listView,
  ArrayAdapter<String> adapter,LinkedList<String> listItems) {
 // TODO            
 mPullRefreshListView = listView;
 mAdapter = adapter;
 mListItems = listItems;
 }
 
 @Override
 protected Void doInBackground(Void... params) {
 //    
 try {
  Thread.sleep(2000);
 } catch (InterruptedException e) {
 }
 return null;
 }
 
 @Override
 protected void onPostExecute(Void result) {
 // TODO          
 super.onPostExecute(result);
 //       
 Mode mode = mPullRefreshListView.getCurrentMode();
 if(mode == Mode.PULL_FROM_START) {
  mListItems.addFirst("         ");
 }
 else {
  mListItems.addLast("         ");
 }
 //        
 mAdapter.notifyDataSetChanged();
 //          
 mPullRefreshListView.onRefreshComplete();
 
 }
 


}

acitivtyの全コードを貼り付けます。 
MainActivity.java 

package com.kale.ptrlistviewtest;

import java.util.Arrays;
import java.util.LinkedList;

import android.app.Activity;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;

public class MainActivity extends Activity {
 
 //         listView  
 private PullToRefreshListView mPullRefreshListView;
 //   listview  
 private ListView actualListView;
 //        ,   string  ,         string       
 private LinkedList<String> mListItems;
 // listview          
 private ArrayAdapter<String> mAdapter;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 initView();

 //          ,              
 mPullRefreshListView.setRefreshing(true);
 //new GetDataTask(mPullRefreshListView, mAdapter, mListItems).execute();
 //mPullRefreshListView.setRefreshing(false);

 }

 private void initView() {
 initPTRListView();
 initListView();
 }
 
 /**
 *        listview   
 */
 private void initPTRListView() {
 mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
 //       
 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);

  //      label
  refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
  //         ,            
  new GetDataTask(mPullRefreshListView, mAdapter,mListItems).execute();
  }
 });

 //            
 mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
  
  @Override
  public void onLastItemVisible() {
  Toast.makeText(getApplication(), "     ", Toast.LENGTH_SHORT).show();
  }
 });
 
 //mPullRefreshListView.isScrollingWhileRefreshingEnabled();//          
 //          
 mPullRefreshListView.setScrollingWhileRefreshingEnabled(true);
 //mPullRefreshListView.getMode();//    
 //          。       :Mode.PULL_FROM_START,Mode.BOTH,PULL_FROM_END
 mPullRefreshListView.setMode(Mode.BOTH);
 
 /**
  *       
  */
 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    
 */
 private void initListView() {
 //  getRefreshableView()     listview  
 actualListView = mPullRefreshListView.getRefreshableView();
 
 String []data = new String[] {"android","ios","wp","java","c++","c#"};
 mListItems = new LinkedList<String>();
 // string    string      
 mListItems.addAll(Arrays.asList(data));
 
 mAdapter = new ArrayAdapter<>(getApplicationContext(), 
  android.R.layout.simple_list_item_1, mListItems);
 actualListView.setAdapter(mAdapter);
 }
}
ソースのダウンロード:http://xiazai.jb51.net/201609/yuanma/AndroidListView(jb 51.net)rar
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。