title: 實(shí)現(xiàn)開(kāi)發(fā)者頭條APP(五)--RecyclerView下拉刷新上拉加載
tags: -RecyclerView,下拉刷新,上拉加載更多
grammar_cjkRuby: true
一 廷支、前言
最近實(shí)在太忙付鹿,一個(gè)多禮拜沒(méi)有更新文章了蝌数,于是今晚加班加點(diǎn)把demo寫(xiě)出來(lái)入桂,現(xiàn)在都12點(diǎn)了才開(kāi)始寫(xiě)文章概作。
1.我們的目標(biāo)
把RecyclerView下拉刷新上拉加載更多加入到我們的開(kāi)發(fā)者頭條APP中厦酬。
2.效果圖
3.實(shí)現(xiàn)步驟
- 找一個(gè)帶上拉刷新下載加載更多的RecyclerView開(kāi)源庫(kù)官帘,我們要站在巨人的肩膀上
- 下載下來(lái)自己先運(yùn)行下demo计雌,然后看看是不是我們需要的功能,覺(jué)得不錯(cuò)就把module依賴(lài)進(jìn)來(lái)训唱,整合主項(xiàng)目褥蚯。
- 整合進(jìn)來(lái)了之后,我們肯定需要進(jìn)行修改况增,例如我這邊就有滑動(dòng)沖突赞庶,有多個(gè)headView等問(wèn)題。
二 澳骤、具體實(shí)現(xiàn)
1.尋找RecyclerView上拉刷新下載加載開(kāi)源庫(kù)
我們找開(kāi)源項(xiàng)目肯定首選github歧强,去搜索一下一大堆,如果效果圖是你想要的功能的話(huà)为肮,然后找排名靠前摊册,收藏比較多的項(xiàng)目吧,我找的項(xiàng)目是CommonPullToRefresh,支持ListView颊艳,RecyclerView茅特,GridView,SwipeRefreshLayout等常用控件棋枕。我跑了一下Demo白修,沒(méi)啥bug,挺好用的重斑。
2.加入項(xiàng)目中
1).module導(dǎo)入進(jìn)來(lái)兵睛,然后主項(xiàng)目依賴(lài)一下,這里有不會(huì)的看我另外一篇文章Android Studio 入門(mén)窥浪,里面有講到Android Studio添加項(xiàng)目依賴(lài)祖很。
2).代碼實(shí)現(xiàn),我們這邊就是修改SelectedFragment
首先我們看布局文件的變化,在RecyclerView外面包裹了自定義的一個(gè)類(lèi)PtrClassicFrameLayout,內(nèi)部實(shí)現(xiàn)了下拉刷新,上拉加載更多漾脂。還可以設(shè)置自定義屬性突琳,都是啥意思我就不解釋了,有興趣的點(diǎn)擊github上那個(gè)鏈接符相,講解的很詳細(xì)拆融。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.chanven.lib.cptr.PtrClassicFrameLayout xmlns:cube_ptr="http://schemas.android.com/apk/res-auto"
android:id="@+id/test_recycler_view_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
cube_ptr:ptr_duration_to_close="200"
cube_ptr:ptr_duration_to_close_header="700"
cube_ptr:ptr_keep_header_when_refresh="true"
cube_ptr:ptr_pull_to_fresh="false"
cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
cube_ptr:ptr_resistance="1.8">
<android.support.v7.widget.RecyclerView
android:id="@+id/test_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"/>
</com.chanven.lib.cptr.PtrClassicFrameLayout>
</LinearLayout>
再來(lái)看onCreateView方法,這個(gè)代碼就不解釋了啊终。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
View rootView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_selected, null);
ptrClassicFrameLayout = (PtrClassicFrameLayout) rootView.findViewById(R.id.test_recycler_view_frame);
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.test_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
init();
return rootView;
}
在onCreateView里面調(diào)用了init()方法镜豹,我們來(lái)瞧瞧怎么實(shí)現(xiàn)的。這里解釋一下為什么要對(duì)適配器進(jìn)行包裝蓝牲,這樣的目的在包裝類(lèi)里面處加入頭部趟脂,底部View,處理點(diǎn)擊事件例衍。大家拿到源碼了之后自己也可以看看昔期。
private void init() {
//初始化適配器
selectedAdapter = new SelectedRecyclerAdapter(getActivity());
//對(duì)適配器進(jìn)行封裝
mAdapter = new RecyclerAdapterWithHF(selectedAdapter);
//把滾動(dòng)Banner加入頭部
mAdapter.addCarouse(initCarouselHead());
mRecyclerView.setAdapter(mAdapter);
ptrClassicFrameLayout.setPtrHandler(ptrDefaultHandler);//設(shè)置下拉監(jiān)聽(tīng)
ptrClassicFrameLayout.setOnLoadMoreListener(onLoadMoreListener);//設(shè)置上拉監(jiān)聽(tīng)
ptrClassicFrameLayout.setLoadMoreEnable(true);//設(shè)置可以加載更多
}
mAdapter.addCarouse(initCarouselHead()); 初始化一個(gè)滾動(dòng)Banner已卸,然后加入適配器頭部。這個(gè)我前面的教程應(yīng)該已經(jīng)講過(guò)了硼一。累澡。
//初始化
private View initCarouselHead(){
View headView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_selected_header,mRecyclerView,false);
tvContent=(TextView) headView.findViewById(R.id.tv_content);
tvContent.setText(carousePageStr[0]);
viewPager = (ViewPager)headView.findViewById(R.id.viewpager);
selectedPagerAdapter=new SelectedPagerAdapter(getActivity(),carousePagerSelectView);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.addOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(selectedPagerAdapter);
ViewGroup group = (ViewGroup) headView.findViewById(R.id.viewGroup);// 初始化底部顯示控件
tips = new ImageView[3];
for (int i = 0; i < tips.length; i++){
ImageView imageView = new ImageView(getActivity());
if (i == 0) {
imageView.setBackgroundResource(R.mipmap.page_indicator_focused);
} else {
imageView.setBackgroundResource(R.mipmap.page_indicator_unfocused);
}
tips[i] = imageView;
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
layoutParams.leftMargin = 10;// 設(shè)置點(diǎn)點(diǎn)點(diǎn)view的左邊距
layoutParams.rightMargin = 10;// 設(shè)置點(diǎn)點(diǎn)點(diǎn)view的右邊距
group.addView(imageView, layoutParams);
}
timer = new Timer(true);//初始化計(jì)時(shí)器
timer.schedule(task, 0, CAROUSEL_TIME);//延時(shí)0ms后執(zhí)行,3000ms執(zhí)行一次
return headView;
}
SelectedRecyclerAdapter 必須繼承RecyclerView.Adapter
這玩意跟ListView的適配器差不多,用過(guò)ListView適配器的應(yīng)該一看就懂了般贼。
首先會(huì)調(diào)用getItemCount愧哟,知道我要顯示多少item。
知道了行數(shù)然后就是循環(huán)調(diào)用onCreateViewHolder跟onBindViewHolder了哼蛆,onCreateViewHolder就是創(chuàng)建一個(gè)item的View,onBindViewHolder就會(huì)把上次創(chuàng)建的item的View傳入進(jìn)來(lái)蕊梧,還有一個(gè)下標(biāo),這樣我們就能給每一行賦值腮介,這兩個(gè)方法都是先后一起調(diào)用肥矢。item回收重用的機(jī)制應(yīng)該跟ListView一樣的。
public class SelectedRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<SelectedArticle> selectedArticles;
private LayoutInflater inflater;
public SelectedRecyclerAdapter(Context context) {
super();
inflater = LayoutInflater.from(context);
selectedArticles = new ArrayList<SelectedArticle>();
initData();
}
private void initData() {
for (int i = 0; i < 10; i++) {
SelectedArticle selectedArticle = new SelectedArticle(i, "Android開(kāi)發(fā)666", i, i, "");
selectedArticles.add(selectedArticle);
}
}
public void loadMore(int page) {
for (int i = 0; i < 5; i++) {
SelectedArticle selectedArticle = new SelectedArticle(i, "第" + page + "頁(yè)數(shù)據(jù)", i, i, "");
selectedArticles.add(selectedArticle);
}
}
public void getFirst() {
selectedArticles.clear();
initData();
}
@Override
public int getItemCount() {
return selectedArticles.size();
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
SelectedRecyclerHolder holder = (SelectedRecyclerHolder) viewHolder;
SelectedArticle selectedArticle = selectedArticles.get(position);
holder.title.setText(selectedArticle.getTitle());
holder.like.setText("" + selectedArticle.getLikeNumber());
holder.comment.setText("" + selectedArticle.getCommentNumber());
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewHolder, int position) {
View view = inflater.inflate(R.layout.fragment_selected_item, null);
return new SelectedRecyclerHolder(view);
}
public class SelectedRecyclerHolder extends RecyclerView.ViewHolder {
private TextView title;//標(biāo)題
private TextView like;//喜歡數(shù)量
private TextView comment;評(píng)論數(shù)量
public SelectedRecyclerHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.tv_title);
like = (TextView) view.findViewById(R.id.tv_like);
comment = (TextView) view.findViewById(R.id.tv_comment);
}
}
}
3.解決整合進(jìn)來(lái)的bug
- 滑動(dòng)沖突
當(dāng)我們上拉到頂部把標(biāo)題欄擠出屏幕外的時(shí)候,進(jìn)行下拉會(huì)觸發(fā)RecyclerView的下拉事件叠洗,正確的情況應(yīng)該是顯示Toolbar.
1).RecyclerView下拉刷新的時(shí)候先判斷Toolbar有沒(méi)有顯示甘改。如果Toolbar沒(méi)有顯示就不處理。
2).AppBarLayout有一個(gè)addOnOffsetChangedListener方法,在AppBarLayout的布局偏移量發(fā)生改變時(shí)被調(diào)用惕味。
在MainFragment里面進(jìn)行監(jiān)聽(tīng)
appBarLayout= (AppBarLayout) rootView.findViewById(R.id.appBarLayout);
appBarLayout.addOnOffsetChangedListener(onOffsetChangedListener);
然后在回調(diào)函數(shù)中楼誓,把值給SelectedFragment玉锌,
private AppBarLayout.OnOffsetChangedListener onOffsetChangedListener=new AppBarLayout.OnOffsetChangedListener() {
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int i){
//i>=0 Toolbar全部顯示
selectedFragment.setPullRefresh(i>=0);
System.out.println("i值:"+i);
}
};
3).在SelectedFragment中名挥,繼續(xù)把值傳給PtrFrameLayout
public void setPullRefresh(boolean pullRefresh) {
ptrClassicFrameLayout.setPullRefresh(pullRefresh);
}
4.在PtrFrameLayout里面用一個(gè)實(shí)例變量接收這個(gè)值
private boolean pullRefresh=true;
public void setPullRefresh(boolean pullRefresh) {
this.pullRefresh = pullRefresh;
}
4).找到PtrFrameLayout類(lèi)的dispatchTouchEvent事件,這個(gè)方法是處理屏幕的觸摸事件的。
@Override
public boolean dispatchTouchEvent(MotionEvent e) {
if (!isEnabled() || mContent == null || mHeaderView == null) {
System.out.println("都是空的...");
return dispatchTouchEventSupper(e);
}
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_UP:
System.out.println("彈起...");
case MotionEvent.ACTION_CANCEL:
System.out.println("取消...");
// if(pullRefresh){
mPtrIndicator.onRelease();
if (mPtrIndicator.hasLeftStartPosition()) {
if (DEBUG) {
PtrCLog.d(LOG_TAG, "call onRelease when user release");
}
System.out.println("call onRelease when user release");
onRelease(false);
if (mPtrIndicator.hasMovedAfterPressedDown()) {
sendCancelEvent();
return true;
}
}
return dispatchTouchEventSupper(e);
// }
case MotionEvent.ACTION_DOWN:
System.out.println("按下...");
mHasSendCancelEvent = false;
mPtrIndicator.onPressDown(e.getX(), e.getY());
mScrollChecker.abortIfWorking();
mPreventForHorizontal = false;
// The cancel event will be sent once the position is moved.
// So let the event pass to children.
// fix #93, #102
return dispatchTouchEventSupper(e);
case MotionEvent.ACTION_MOVE:
System.out.println("移動(dòng)...");
if(pullRefresh){//Toolbar顯示
mLastMoveEvent = e;
mPtrIndicator.onMove(e.getX(), e.getY());
float offsetX = mPtrIndicator.getOffsetX();
float offsetY = mPtrIndicator.getOffsetY();
if (mDisableWhenHorizontalMove && !mPreventForHorizontal && (Math.abs(offsetX) > mPagingTouchSlop && Math.abs(offsetX) > Math.abs(offsetY))) {
if (mPtrIndicator.isInStartPosition()) {
mPreventForHorizontal = true;
}
}
if (mPreventForHorizontal) {
return dispatchTouchEventSupper(e);
}
boolean moveDown = offsetY > 0;
boolean moveUp = !moveDown;
boolean canMoveUp = mPtrIndicator.hasLeftStartPosition();
if (DEBUG) {
boolean canMoveDown = mPtrHandler != null && mPtrHandler.checkCanDoRefresh(this, mContent, mHeaderView);
PtrCLog.v(LOG_TAG, "ACTION_MOVE: offsetY:%s, currentPos: %s, moveUp: %s, canMoveUp: %s, moveDown: %s: canMoveDown: %s", offsetY, mPtrIndicator.getCurrentPosY(), moveUp, canMoveUp, moveDown, canMoveDown);
}
// disable move when header not reach top
if (moveDown && mPtrHandler != null && !mPtrHandler.checkCanDoRefresh(this, mContent, mHeaderView)) {
return dispatchTouchEventSupper(e);
}
if ((moveUp && canMoveUp) || moveDown) {
// System.out.println("是否下拉刷新:"+pullRefresh+"偏移量是多少:"+offsetY);
movePos(offsetY);
return true;
}
}
}
return dispatchTouchEventSupper(e);
}
我就改了一行代碼主守,在action==MotionEvent.ACTION_MOVE的時(shí)候禀倔,先判斷我們傳入的pullRefresh是否為true。参淫。救湖。
- 頂部加入輪播
RecyclerView頭部底部加入View,前面我們介紹過(guò)了涎才,都是適配器的封裝類(lèi)RecyclerAdapterWithHF來(lái)控制鞋既。從效果圖中,我們可以看出耍铜,輪播的View是加入頭部的邑闺,找到RecyclerAdapterWithHF類(lèi),看看源碼依葫蘆畫(huà)瓢就可以了棕兼。
1).得有一個(gè)保存View的集合陡舅,其實(shí)用一個(gè)變量也行,因?yàn)槲覀冎挥幸粋€(gè)輪播View.
private List<View> mCarouse = new ArrayList<View>();//保存輪播View
//可以添加輪播View
public void addCarouse(View view){
mCarouse.add(view);
}
2).定義一個(gè)常量伴挚,用于類(lèi)型判斷
public static final int TYPE_CAROUSE = 7900;
3).在getItemViewType里面加入輪播的類(lèi)型
@Override
public final int getItemViewType(int position) {
// check what type our position is, based on the assumption that the
// order is headers > items > footers
if (isHeader(position)) {
return TYPE_HEADER;
} else if (mCarouse.size()>0&&mHeaders.size()==position){ //判斷集合個(gè)數(shù)&&position==0 這個(gè)時(shí)候mHeaders里面是沒(méi)有值的
return TYPE_CAROUSE;
}else if (isFooter(position)) {
return TYPE_FOOTER;
}
int type = getItemViewTypeHF(getRealPosition(position));
if (type == TYPE_HEADER || type == TYPE_FOOTER|| type == TYPE_CAROUSE) {
throw new IllegalArgumentException("Item type cannot equal " + TYPE_HEADER + " or " + TYPE_FOOTER);
}
return type;
}
4).onCreateViewHolder里面也要修改一下靶衍,就是在if里面多加了個(gè)&&.無(wú)論是頭部灾炭,底部,輪播的View颅眶,都是添加到FrameLayout里面的蜈出。
@Override
public final RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int type) {
// if our position is one of our items (this comes from
// getItemViewType(int position) below)
if (type != TYPE_HEADER && type != TYPE_FOOTER && type != TYPE_CAROUSE) {
ViewHolder vh = onCreateViewHolderHF(viewGroup, type);
return vh;
// else we have a header/footer
} else {
// create a new framelayout, or inflate from a resource
FrameLayout frameLayout = new FrameLayout(viewGroup.getContext());
// make sure it fills the space
frameLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return new HeaderFooterViewHolder(frameLayout);
}
}
5).onBindViewHolder這里為item綁定數(shù)據(jù),其實(shí)就是第四步返回的ItemView綁定數(shù)據(jù).
@Override
public final void onBindViewHolder(final RecyclerView.ViewHolder vh, int position){
// check what type of view our position is
if (isHeader(position)) {
View v = mHeaders.get(position);
// add our view to a header view and display it
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
}else if(mCarouse.size()>0&&position==mHeaders.size()){//這個(gè)時(shí)候mHeaders.size()值為0
// System.out.println("有多少個(gè)頭View:"+mHeaders.size()+"值等于多少:"+(mHeaders.size()-1));
View v = mCarouse.get(mHeaders.size());//取出輪播的View
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
} else if (isFooter(position)) {
View v = mFooters.get(position - getItemCountHF() - mHeaders.size());
// add our view to a footer view and display it
prepareHeaderFooter((HeaderFooterViewHolder) vh, v);
} else {
vh.itemView.setOnClickListener(new MyOnClickListener(vh));
vh.itemView.setOnLongClickListener(new MyOnLongClickListener(vh));
// it's one of our items, display as required
onBindViewHolderHF(vh, getRealPosition(position));
}
}
6).我們從第五步看到頭部底部輪播View最后都會(huì)調(diào)用prepareHeaderFooter方法帚呼√投校看到這方法的源碼,其實(shí)就是把類(lèi)型對(duì)應(yīng)的View煤杀,添加到Item中.
private void prepareHeaderFooter(HeaderFooterViewHolder vh, View view) {
// if it's a staggered grid, span the whole layout
if (mManagerType == TYPE_MANAGER_STAGGERED_GRID) {
StaggeredGridLayoutManager.LayoutParams layoutParams = new StaggeredGridLayoutManager.LayoutParams
(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setFullSpan(true);
vh.itemView.setLayoutParams(layoutParams);
}
// if the view already belongs to another layout, remove it
if (view.getParent() != null) {
((ViewGroup) view.getParent()).removeView(view);
}
// empty out our FrameLayout and replace with our header/footer
vh.base.removeAllViews();
vh.base.addView(view);
}
三眷蜈、源碼下載
四 、相關(guān)文章閱讀
帶你實(shí)現(xiàn)開(kāi)發(fā)者頭條(一) 啟動(dòng)頁(yè)實(shí)現(xiàn)
帶你實(shí)現(xiàn)開(kāi)發(fā)者頭條(二) 實(shí)現(xiàn)左滑菜單
帶你實(shí)現(xiàn)開(kāi)發(fā)者頭條APP(三) 首頁(yè)實(shí)現(xiàn)
帶你實(shí)現(xiàn)開(kāi)發(fā)者頭條APP(四) 首頁(yè)優(yōu)化(加入design包)
各位看官如果覺(jué)得文章不錯(cuò)沈自,幫忙點(diǎn)個(gè)贊吧酌儒,對(duì)于你來(lái)說(shuō)是舉手之勞,但對(duì)于我來(lái)說(shuō)這就是堅(jiān)持下去的動(dòng)力枯途。
如果你想第一時(shí)間看我們的后期文章忌怎,掃碼關(guān)注公眾號(hào),每周不定期推送Android開(kāi)發(fā)實(shí)戰(zhàn)教程文章酪夷,你還等什么榴啸,趕快關(guān)注吧,學(xué)好技術(shù)晚岭,出任ceo鸥印,贏取白富美。坦报。库说。。
Android開(kāi)發(fā)666 - 安卓開(kāi)發(fā)技術(shù)分享
掃描二維碼加關(guān)注