RecyclerView

原生recyclerView

gradle

dependencies {
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
}

xml

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swipe_refresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent"">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</android.support.v4.widget.SwipeRefreshLayout>

Activity

//Init
@BindView(R.id.swipe_refresh)
SwipeRefreshLayout swipeRefresh;
@BindView(R.id.rv_content)
RecyclerView rvContent;

private List<MBean> mList = new ArrayList<>();
private MAdapter mAdapter;

//onCreate
swipeRefresh.setRefreshing(true);
swipeRefresh.setColorSchemeResources(R.color.colorBG);
mAdapter = new MAdapter(mContext, mList);
rvContent.setLayoutManager(new LinearLayoutManager(mContext));
rvContent.setAdapter(mAdapter);
mPresenter.getList(id);

swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        mPresenter.getList(id);
    }
});

mAdapter.setOnItemClickListener(new MAdapter.OnItemClickListener() {
    @Override
    public void onItemClick(int position) {
        mAdapter.notifyItemChanged(position);
    }
});

//show
@Override
public void showList(List<MBean> list) {
    if(swipeRefresh.isRefreshing())
        swipeRefresh.setRefreshing(false);
    mAdapter.setLists(list);
    mAdapter.notifyDataSetChanged();
}

Presenter

@Override
public void getList(Integer id) {
    Subscription rxSubscription = mRetrofitHelper.getList(id)
        .compose(RxUtil.<MyHttpResponse<List<MBean>>>rxSchedulerHelper())
        .compose(RxUtil.<List<MBean>>handleMyResult())
        .subscribe(new Action1<List<MBean>>() {
            @Override
            public void call(List<MBean> list) {
                mView.showList(list);
            }
         }, new Action1<Throwable>() {
             @Override
             public void call(Throwable throwable) {
                 throwable.printStackTrace();
                 mView.showError("數(shù)據(jù)加載失敗ヽ(≧Д≦)ノf");
             }
         });
     addSubscrebe(rxSubscription);
}

Adapter

public class MAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<MBean> mList;
    private Context mContext;
    private OnItemClickListener onItemClickListener;

    public MAdapter(Context mContext, List<MBean> mList) {
        this.mList = mList;
        this.mContext = mContext;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        Glide.with(mContext).load(mList.get(position).getImage())
           .placeholder(R.drawable.null_img)
           .error(R.drawable.null_img)
           .into(((ViewHolder) holder).ivImage);

        ((ViewHolder) holder).tvNumber.setText(String.valueOf(mList.get(position).getId()));
        ((ViewHolder) holder).tvType.setText(
                mContext.getResources().getStringArray(R.array.type)
                [mList.get(position).geType()]);

        ((ViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(onItemClickListener != null) {
                   onItemClickListener.onItemClick(holder.getAdapterPosition());
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public void setLists(List<MBean> list) {
        mList.clear();
        mList.addAll(list);
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_image)
        ImageView ivImage;
        @BindView(R.id.tv_number)
        TextView tvNumber;
        @BindView(R.id.tv_type)
        TextView tvType;

        ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}

R.layout.item

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:descendantFocusability="blocksDescendants"
    app:cardCornerRadius="2dp"
    app:cardElevation="2dp"
    app:contentPadding="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/iv_image"
            android:layout_width="160dp"
            android:layout_height="110dp"
            android:scaleType="centerCrop"
            android:src="@drawable/null_img"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="5dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="No:"
                    android:textSize="15sp"/>

                <TextView
                    android:id="@+id/tv_number"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp"/>

                <TextView
                    android:id="@+id/tv_type"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>

        </LinearLayout >

    </LinearLayout>

</android.support.v7.widget.CardView>

PS:多布局Adapter

public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private List<ImageFlagBean> mList;
    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClickDefaultPole(View view);
        void onItemClickDefaultSign(View view);
        void onItemClick(View view, Integer position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public ImageAdapter(Context mContext, List<ImageFlagBean> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        if(viewType == 1) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_recycler_image_default, parent, false);
            viewHolder = new ViewHolderDefaultPole(view);
        } else if(viewType == 2) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_recycler_image_default, parent, false);
            viewHolder = new ViewHolderDefaultSign(view);
        } else if(viewType == 3) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_recycler_image, parent, false);
            viewHolder = new ViewHolder(view);
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        if(holder instanceof ViewHolder) {
            ((ViewHolder) holder).ivRecycler.setImageBitmap(mList.get(position).getImage());
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onItemClickListener != null) {
                        onItemClickListener.onItemClick(holder.itemView, position);
                    }
                }
            });
        } else if(holder instanceof ViewHolderDefaultPole) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onItemClickListener != null) {
                        onItemClickListener.onItemClickDefaultPole(holder.itemView);
                    }
                }
            });
        } else if(holder instanceof ViewHolderDefaultSign) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(onItemClickListener != null) {
                        onItemClickListener.onItemClickDefaultSign(holder.itemView);
                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    @Override
    public int getItemViewType(int position) {
        int result = 0;
        if(mList.get(position).getFlag() == 1)
            result = 1;
        else if(mList.get(position).getFlag() == 2)
            result = 2;
        else if(mList.get(position).getFlag() == 3)
            result = 3;
        return result;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_recycler)
        ImageView ivRecycler;

        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    static class ViewHolderDefaultPole extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_recycler_default)
        ImageView ivRecyclerDefault;

        ViewHolderDefaultPole(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    static class ViewHolderDefaultSign extends RecyclerView.ViewHolder {
        @BindView(R.id.iv_recycler_default)
        ImageView ivRecyclerDefault;

        ViewHolderDefaultSign(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

}

懶加載recyclerView

Github原址

gradle

dependencies {
    compile 'com.wuxiaolong.pullloadmorerecyclerview:library:1.1.2'
}

xml

<com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView
        android:id="@+id/rv_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

Activity

    //Init
    @BindView(R.id. rv_content)
    PullLoadMoreRecyclerView rvContent;

    private MAdapter mAdapter;
    private Integer mCount;

    //onCreate
    rvContent.setLinearLayout();
    rvContent.setColorSchemeResources(R.color.colorBG);
    rvContent.setRefreshing(true);
    rvContent.setFooterViewText("正在加載");
    mAdapter = new MAdapter(mContext);
    rvContent.setAdapter(mAdapter);
    rvContent.setOnPullLoadMoreListener(new
PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                mCount = 1;
                mAdapter.clearData();
                mPresenter. getList(id, mCount);
            }

            @Override
            public void onLoadMore() {
                mCount++;
                mPresenter. getList(id, mCount);
            }
        });

    //onResume
    @Override
    protected void onResume() {
        super.onResume();
        mCount = 1;
        mAdapter.clearData();
        mPresenter. getList(id, mCount);
    }

   //show
   @Override
    public void showList(List<MBean> list) {
        mAdapter.addAllData(list);
        rvContent.setPullLoadMoreCompleted();
    }

Presenter

public void getList(Integer id, Integer mCount) {
        Subscription rxSubscription = mRetrofitHelper.getList(id,mCount)
                .compose(RxUtil.<MyHttpResponse<List<MBean>>>rxSchedulerHelper())
                .compose(RxUtil.<List<MBean>>handleMyResult())
                .subscribe(new Action1<List<MBean>>() {
                    @Override
                    public void call(List<MBean> list) {
                        mView.showList(list);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                        mView.showError("數(shù)據(jù)加載失敗ヽ(≧Д≦)ノf");
                    }
                });
        addSubscrebe(rxSubscription);
    }

Adapter

public class MAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context mContext;
    private List<MBean> mList = new ArrayList<>();

    public FaultHandleAdapter(Context mContext) {
        this.mContext = mContext;
    }

    public void addAllData(List<MBean> list) {
        mList.addAll(list);
        notifyDataSetChanged();
    }

    public void clearData() {
        this.mList.clear();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_fault, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        ((MainViewHolder) holder).itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, SomeActivity.class);
                intent.putExtra("id", mList.get(holder.getAdapterPosition()).getId());
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    static class MainViewHolder extends RecyclerView.ViewHolder {
        MainViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
    
}

懶加載后臺(tái)

Controller

    @RequestMapping("/getList")
    @ResponseBody
    public JsonMsgDto getList(Integer id, Integer mCount, Integer mSize) {
        JsonMsgDto jsonMsgDto = new JsonMsgDto();
        try {
            jsonMsgDto.setJsonData(mService. getList(id, mCount, mSize));
            jsonMsgDto.setIsSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonMsgDto.setIsSuccess(false);
        }
        return jsonMsgDto;
    }

Service

@Override
    public List<MDto> getList(Integer id, Integer mCount, Integer mSize) throws Exception {
        return mRepository. getList(id,  mCount, mSize);
    }

Repository

public List<MDto> getList(Integer id, Integer mCount, Integer mSize) throws Exception {
        String sql = "select m.*, n.* " +
                "from tb_m m, tb_n n " +
                "where m.p = n.p";
        //MDto 的字段必須包含所有的 tb_m 和 tb_n 的字段
        Query query = em.createNativeQuery(sql);
        query.unwrap(NativeQuery.class).setResultTransformer(Transformers.aliasToBean(MDto.class));
        return query.setFirstResult((mCount - 1) * mySize).setMaxResults(mSize).getResultList();
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子篇恒,更是在濱河造成了極大的恐慌秒梅,老刑警劉巖,帶你破解...
    沈念sama閱讀 212,383評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件貌亭,死亡現(xiàn)場(chǎng)離奇詭異稠腊,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)子眶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,522評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)序芦,“玉大人壹店,你說(shuō)我怎么就攤上這事≈ゼ樱” “怎么了硅卢?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,852評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)藏杖。 經(jīng)常有香客問(wèn)我将塑,道長(zhǎng),這世上最難降的妖魔是什么蝌麸? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,621評(píng)論 1 284
  • 正文 為了忘掉前任点寥,我火速辦了婚禮,結(jié)果婚禮上来吩,老公的妹妹穿的比我還像新娘敢辩。我一直安慰自己,他們只是感情好弟疆,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,741評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布戚长。 她就那樣靜靜地躺著,像睡著了一般怠苔。 火紅的嫁衣襯著肌膚如雪同廉。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 49,929評(píng)論 1 290
  • 那天柑司,我揣著相機(jī)與錄音迫肖,去河邊找鬼。 笑死攒驰,一個(gè)胖子當(dāng)著我的面吹牛蟆湖,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播玻粪,決...
    沈念sama閱讀 39,076評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼隅津,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了奶段?” 一聲冷哼從身側(cè)響起饥瓷,我...
    開(kāi)封第一講書(shū)人閱讀 37,803評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎痹籍,沒(méi)想到半個(gè)月后呢铆,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,265評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蹲缠,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,582評(píng)論 2 327
  • 正文 我和宋清朗相戀三年棺克,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了悠垛。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,716評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡娜谊,死狀恐怖确买,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情纱皆,我是刑警寧澤湾趾,帶...
    沈念sama閱讀 34,395評(píng)論 4 333
  • 正文 年R本政府宣布,位于F島的核電站派草,受9級(jí)特大地震影響搀缠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜近迁,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,039評(píng)論 3 316
  • 文/蒙蒙 一艺普、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧鉴竭,春花似錦歧譬、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至祭埂,卻和暖如春面氓,著一層夾襖步出監(jiān)牢的瞬間兵钮,已是汗流浹背蛆橡。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,027評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留掘譬,地道東北人泰演。 一個(gè)月前我還...
    沈念sama閱讀 46,488評(píng)論 2 361
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像葱轩,于是被迫代替她去往敵國(guó)和親睦焕。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,612評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 171,838評(píng)論 25 707
  • 目錄 ? 1. RecyclerView與ListView的異同 ? 2. RecyclerView的使用...
    plus1s閱讀 1,209評(píng)論 0 10
  • 首先介紹下RecyclerView靴拱,RecyclerView相比ListView增加了很多新特性: ? Adapt...
    LucasAdam閱讀 2,829評(píng)論 0 6
  • made Fast and Easy字?jǐn)?shù)2326 閱讀79 評(píng)論0 喜歡1Fastadapter使Recycler...
    一直以來(lái)都很好閱讀 1,150評(píng)論 2 0
  • 走進(jìn)你的視線垃喊,卻無(wú)法摸索你的心。 淚雨相伴的顏容袜炕,憔悴風(fēng)干的冬季本谜。 所有留住的日子,在素色的風(fēng)鈴聲中老去偎窘。 愛(ài)情潮...
    河的岸與岸閱讀 220評(píng)論 0 0