RecyclerView的使用

1.RecylerView是什么

RecylerView是support-v7包中的新組件辽聊,和ListView一樣有item回收復(fù)用的功能,同時(shí),又是listView的升級(jí)版,它封裝了viewholder的回收復(fù)用搔涝,也就是說(shuō)RecylerView標(biāo)準(zhǔn)化了ViewHolder黍图,編寫Adapter面向的是ViewHolder而不再是View了曾雕;它提供了一種插拔式的體驗(yàn),高度的解耦助被,異常的靈活剖张,針對(duì)一個(gè)Item的顯示RecyclerView專門抽取出了相應(yīng)的類,來(lái)控制Item的顯示揩环,使其的擴(kuò)展非常強(qiáng)搔弄。

2.ViewHolder和Adapter

RecyclerView的任務(wù)僅限于回收和定位屏幕上的View。還有另外兩個(gè)類:ViewHoler和Adapter丰滑。
ViewHolder就是容納View視圖顾犹。
Adapter創(chuàng)建必要的ViewHoler,綁定ViewHoler至模型層數(shù)據(jù)

3.使用RecylerView

先要添加RecylerView依賴庫(kù),單擊File->Project Structure菜單項(xiàng)切換至項(xiàng)目結(jié)構(gòu)窗口褒墨,選擇左邊的app模塊炫刷,單機(jī)Dependencies選項(xiàng)頁(yè),單擊+按鈕添加依賴庫(kù)


image.png

也可以在build.gradle中添加郁妈,如圖


image.png

這里的例子是帖子信息顯示
我們可以新建一個(gè)fragment_post_list布局文件浑玛,修改根視圖為RecyclerView

<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/post_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>

下面是視圖和fragment關(guān)聯(lián),新建PostListFragment文件噩咪,讓他的布局為RecyclerView

public class PostListFragment extends Fragment {
    private RecyclerView mPostRecyclerView;

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_post_list,container,false);

        mPostRecyclerView=(RecyclerView)view.findViewById(R.id.post_recycler_view);
        mPostRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return view;
    }

注意這個(gè)時(shí)候如果沒(méi)有LayoutManager我們的RecyclerView無(wú)法工作顾彰,會(huì)導(dǎo)致應(yīng)用崩潰,我們應(yīng)該創(chuàng)建完成后立即交給LayoutManager

現(xiàn)在需要初始的Activity文件中托管我們的fragment文件

public class PostListActivity extends AppCompatActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);

        FragmentManager fm=getSupportFragmentManager();
        Fragment fragment=fm.findFragmentById(R.id.fragment_container);

        if(fragment==null){
            fragment=new PostListFragment();
            fm.beginTransaction()
                    .add(R.id.fragment_container,fragment)
                    .commit();
        }
    }
}

然后運(yùn)行發(fā)現(xiàn)是一個(gè)空的界面


image.png

3.1列表項(xiàng)視圖

我們的列表里面有很多的數(shù)據(jù)胃碾,我們要?jiǎng)?chuàng)建一個(gè)視圖布局一條條根據(jù)自己的需要拜訪它
新建一個(gè)list_item_crime文件

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <TextView
        android:id="@+id/post_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post Title"/>
    <TextView
        android:id="@+id/post_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post Date"/>
</LinearLayout>

3.2實(shí)現(xiàn)ViewHolder涨享、Adapter

我們需要實(shí)例化并使用剛剛新建的list_item_crime布局

定義ViewHolder(PostListFragment.java)
    private class PostHolder extends RecyclerView.ViewHolder{
        public PostHolder(LayoutInflater inflater,ViewGroup parent){
            super(inflater.inflate(R.layout.list_item_post,parent,false));
        }
    }
定義Adapter(PostListFragment.java)
private class PostAdapter extends RecyclerView.Adapter<PostHolder>{
        private List<Post> mPosts;
        public PostAdapter(List<Post> posts){
            mPosts=posts;
        }

        @Override
        public PostHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater=LayoutInflater.from(getActivity());
            return new PostHolder(layoutInflater,parent);
        }

        @Override
        public void onBindViewHolder(PostHolder holder, int position) {
        }

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

接下來(lái)我們要將Adapter和RecyclerView關(guān)聯(lián)起來(lái),實(shí)現(xiàn)一個(gè)設(shè)置PostListFragment用戶界面的updateUI方法书在,創(chuàng)建PostAdapter灰伟,然后設(shè)置給RecyclerView

public class PostListFragment extends Fragment {
    ...
    private PostAdapter mAdapter;
    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_post_list,container,false);

        mPostRecyclerView=(RecyclerView)view.findViewById(R.id.post_recycler_view);
        mPostRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        updateUI();

        return view;
    }
    private void updateUI(){
        PostLab postLab=PostLab.get(getActivity());
        List<Post> posts=postLab.getPosts();

        mAdapter=new PostAdapter(posts);
        mPostRecyclerView.setAdapter(mAdapter);
    }
}
image.png

3.2綁定列表項(xiàng)

讓java代碼和組件關(guān)聯(lián)起來(lái)。

    private class PostHolder extends RecyclerView.ViewHolder {
        private Post mPost;
        private TextView mTitleTextView;
        private TextView mDateTextView;
        public void bind(Post post){
            mPost=post;
            mTitleTextView.setText(mPost.getTitle());
            mDateTextView.setText(mPost.getDate().toString());
        }

        public PostHolder(LayoutInflater inflater,ViewGroup parent){
            super(inflater.inflate(R.layout.list_item_post,parent,false));
            mTitleTextView=(TextView) itemView.findViewById(R.id.post_title);
            mDateTextView=(TextView) itemView.findViewById(R.id.post_date);
        }

現(xiàn)在只要取到一個(gè)Post,PostHolder就會(huì)刷新顯示TextView標(biāo)題視圖和TextView日期視圖儒旬,記得調(diào)用bind(Post)方法

        @Override
        public void onBindViewHolder(PostHolder holder, int position) {
            Post post=mPosts.get(position);
            holder.bind(post);
        }

運(yùn)行


image.png

3.2響應(yīng)點(diǎn)擊

現(xiàn)在先達(dá)到點(diǎn)擊一下彈出一個(gè)toast的效果栏账,RecycleView功能強(qiáng)大,但是要自己處理觸摸事件栈源,雖然它也能幫我們轉(zhuǎn)發(fā)觸摸事件挡爵,不過(guò)大多數(shù)時(shí)候還是沒(méi)必要這么做的
通過(guò)修改PostHolder類處理用戶點(diǎn)擊事件

    private class PostHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        public PostHolder(LayoutInflater inflater,ViewGroup parent){
            super(inflater.inflate(R.layout.list_item_post,parent,false));
            mTitleTextView=(TextView) itemView.findViewById(R.id.post_title);
            mDateTextView=(TextView) itemView.findViewById(R.id.post_date);

            itemView.setOnClickListener(this);
        }
        @Override
        public void onClick(View view) {
            Toast.makeText(getActivity(),mPost.getTitle()+" clicked!",Toast.LENGTH_SHORT).show();
        }
}

點(diǎn)擊某個(gè)列表項(xiàng),可看到彈出的toast響應(yīng)消息


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末甚垦,一起剝皮案震驚了整個(gè)濱河市茶鹃,隨后出現(xiàn)的幾起案子涣雕,更是在濱河造成了極大的恐慌,老刑警劉巖闭翩,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件挣郭,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡疗韵,警方通過(guò)查閱死者的電腦和手機(jī)兑障,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蕉汪,“玉大人流译,你說(shuō)我怎么就攤上這事≌甙蹋” “怎么了福澡?”我有些...
    開封第一講書人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)驹马。 經(jīng)常有香客問(wèn)我革砸,道長(zhǎng),這世上最難降的妖魔是什么窥翩? 我笑而不...
    開封第一講書人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任业岁,我火速辦了婚禮鳞仙,結(jié)果婚禮上寇蚊,老公的妹妹穿的比我還像新娘。我一直安慰自己棍好,他們只是感情好仗岸,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著借笙,像睡著了一般扒怖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上业稼,一...
    開封第一講書人閱讀 51,301評(píng)論 1 301
  • 那天盗痒,我揣著相機(jī)與錄音,去河邊找鬼低散。 笑死俯邓,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的熔号。 我是一名探鬼主播稽鞭,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼引镊!你這毒婦竟也來(lái)了朦蕴?” 一聲冷哼從身側(cè)響起篮条,我...
    開封第一講書人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎吩抓,沒(méi)想到半個(gè)月后涉茧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡疹娶,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年降瞳,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蚓胸。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡挣饥,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出沛膳,到底是詐尸還是另有隱情扔枫,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布锹安,位于F島的核電站短荐,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏叹哭。R本人自食惡果不足惜忍宋,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望风罩。 院中可真熱鬧糠排,春花似錦、人聲如沸超升。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)室琢。三九已至乾闰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間盈滴,已是汗流浹背涯肩。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留巢钓,地道東北人病苗。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像竿报,于是被迫代替她去往敵國(guó)和親铅乡。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

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