以下版本自行更新
compile 'com.android.support:appcompat-v7:21.0.0'
compile 'com.android.support:recyclerview-v7:21.0.0'
compile 'com.android.support:cardview-v7:21.0.0'
compile 'com.android.support:support-v4:21.0.0'
需要解決的問題
[x] 下拉刷新
[x] 自動加載
[x] 網絡請求異步加載
技術處理
下拉刷新
采用 android.support.v4.widget.SwipeRefreshLayout 來實現
具體可以搜索這個class,我們按照官方文檔,布局如下
<view xmlns:android="/apk/res/android"
android:id="@+id/swipeRefreshLayout"
class="android.support.v4.widget.SwipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<view xmlns:android="/apk/res/android"
android:id="@+id/recylerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></view>
</view>
然後對 swipeRefreshLayout 設置監聽即可
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if(isrefreshing){
Log.d(TAG,"ignore manually update!");
} else{
loadPage();
}
}
});
自動加載
RecyclerView是壹個新興事物,伸手黨們還找不到 endless-RecyclerView 這樣的開源神器,只好自己找方法了,同ListView壹樣,還是重寫 OnScrollListener 這個方法
recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int lastVisibleItem = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
int totalItemCount = mLayoutManager.getItemCount();
//lastVisibleItem >= totalItemCount - 4 表示剩下4個item自動加載,各位自由選擇
// dy>0 表示向下滑動
if (lastVisibleItem >= totalItemCount - 4 && dy > 0) {
if(isLoadingMore){
Log.d(TAG,"ignore manually update!");
} else{
loadPage();//這裏多線程也要手動控制isLoadingMore
isLoadingMore = false;
}
}
}
});
如果想用GridView,可以試試這個,註意例子裏的span_count =2
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
int[] visibleItems = mLayoutManager.findLastVisibleItemPositions(null);
int lastitem = Math.max(visibleItems[0],visibleItems[1]);
Log.d(TAG,"visibleItems =" + visibleItems);
Log.d(TAG,"lastitem =" + lastitem);
Log.d(TAG,"adapter.getItemCount() =" + adapter.getItemCount());
if (dy > 0 && lastitem > adapter.getItemCount() - 5 && !isLoadingMore) {
Log.d(TAG,"will loadNewFeeds");
}
}
文/BlackSwift(簡書作者)