RecyclerView

RecyclerView是Android一個(gè)更強(qiáng)大的控件,其不僅可以實(shí)現(xiàn)和ListView同樣的效果,還有優(yōu)化了ListView中的各種不足碟案。其可以實(shí)現(xiàn)數(shù)據(jù)縱向滾動(dòng),也可以實(shí)現(xiàn)橫向滾動(dòng)(ListView做不到橫向滾動(dòng))。接下來講解RecyclerView的用法千康。

RecyclerView 基本用法

因?yàn)?code>RecyclerView屬于新增的控件,Android將RecyclerView定義在support庫里先鱼。若要使用RecyclerView,第一步是要在build.gradle中添加對(duì)應(yīng)的依賴庫。

添加RecyclerView 依賴庫

app/build.gradle中的dependencies閉包添加以下內(nèi)容:

    implementation 'com.android.support:recyclerview-v7:27.1.1'

然后點(diǎn)擊頂部的Sync Now進(jìn)行同步

修改 activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

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

由于RecyclerView不是內(nèi)置在系統(tǒng)SDK中,需要把其完整的包名路徑寫出來

新建 Fruit.java

public class Fruit {

    private String name;
    private int imageId;

    public Fruit(String name, int imageId){
        this.name = name;
        this.imageId = imageId;

    }

    public String getName() {
        return name;
    }

    public int getImageId() {
        return imageId;
    }
}

新建 fruit_item.xml

創(chuàng)建ImageView來顯示水果圖片,TextView來顯示水果名字。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fruit_image"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fruitname"
        android:layout_gravity="center_vertical"
        android:layout_marginLeft="10dp"/>

</LinearLayout>

新增適配器 FruitAdapter

RecyclerView新增適配器FruitAdapter,并讓其繼承于RecyclerView.Adapter,把泛型指定為FruitAdapter.ViewHolder钉稍。

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

    private  List<Fruit> mFruitList;
    static class ViewHolder extends RecyclerView.ViewHolder{
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder (View view)
        {
            super(view);
            fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            fruitName = (TextView) view.findViewById(R.id.fruitname);
        }

    }

    public  FruitAdapter (List <Fruit> fruitList){
        mFruitList = fruitList;
    }

    @Override

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

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

        Fruit fruit = mFruitList.get(position);
        holder.fruitImage.setImageResource(fruit.getImageId());
        holder.fruitName.setText(fruit.getName());
    }

    @Override
    public int getItemCount(){
        return mFruitList.size();
    }
  • 定義內(nèi)部類ViewHolder,并繼承RecyclerView.ViewHolder。傳入的View參數(shù)通常是RecyclerView子項(xiàng)的最外層布局棺耍。

  • FruitAdapter構(gòu)造函數(shù),用于把要展示的數(shù)據(jù)源傳入,并賦予值給全局變量mFruitList贡未。

  • FruitAdapter繼承RecyclerView.Adapter。因?yàn)楸仨氈貙?code>onCreateViewHolder(),onBindViewHolder()getItemCount()三個(gè)方法

    • onCreateViewHolder()用于創(chuàng)建ViewHolder實(shí)例,并把加載的布局傳入到構(gòu)造函數(shù)去,再把ViewHolder實(shí)例返回蒙袍。
    • onBindViewHolder()則是用于對(duì)子項(xiàng)的數(shù)據(jù)進(jìn)行賦值,會(huì)在每個(gè)子項(xiàng)被滾動(dòng)到屏幕內(nèi)時(shí)執(zhí)行俊卤。position得到當(dāng)前項(xiàng)的Fruit實(shí)例。
    • getItemCount()返回RecyclerView的子項(xiàng)數(shù)目害幅。

修改 MainActivity.java

public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

    private void initFruits() {
        for (int i = 0; i < 2; i++) {
            Fruit apple = new Fruit("Apple", R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana", R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit("Orange", R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit watermelon = new Fruit("Watermelon", R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit("Pear", R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit("Grape", R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("Pineapple", R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit("Strawberry", R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit("Cherry", R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit("Mango", R.drawable.mango_pic);
            fruitList.add(mango);

        }
    }
}

LayoutManager用于指定RecyclerView的布局方式消恍。LinearLayoutManager指的是線性布局。

運(yùn)行效果:


image

修改RecyclerView 顯示效果

橫向滾動(dòng)

修改 fruit_item.xml

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

    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fruit_image"
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fruitname"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"/>
</LinearLayout>

把LinearLayout改成垂直排列,因?yàn)樗珠L(zhǎng)度不一樣,把寬度改為100dp以现。
ImageView和TextView都改為水平居中

修改MainActivity.java

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }

通過調(diào)用setOrientation()把布局的排列方向改為水平排列狠怨。

得益于RecyclerView的設(shè)計(jì),我們可以通過LayoutManager實(shí)現(xiàn)各種不同的排列方式的布局。

運(yùn)行結(jié)果:

image

除了LinearLayoutManager,RecyclerView還提供了GridLayoutManager(網(wǎng)格布局)StaggeredGridLayoutManager(瀑布流布局)

GridLayoutManager

GridLayoutManager(網(wǎng)格布局)

修改MainActivity.java

修改 MainActivity.java,把

 LinearLayoutManager layoutManager = new LinearLayoutManager(this);
 layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

換成

GridLayoutManager layoutManager = new GridLayoutManager(this,5);

GridLayoutManager (Context context, int spanCount)

  • Context: Current context, will be used to access resources.
  • spanCount int: The number of columns in the grid(網(wǎng)格的列數(shù))

運(yùn)行結(jié)果:


image

StaggeredGridLayoutManager

StaggeredGridLayoutManager(瀑布流布局)

修改fruit_item.xml

<?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="wrap_content"
    android:layout_margin="5dp"

    >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fruit_image"
        android:layout_gravity="center_horizontal"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fruitname"
        android:layout_gravity="left"
        android:layout_marginTop="10dp"/>

</LinearLayout>

把LinearLayout的寬度設(shè)為match_parent是因?yàn)槠俨剂鞯膶挾仁?根據(jù)布局的列數(shù)來自動(dòng)適配的,而不是固定值 邑遏。(GridLayoutManager也是 根據(jù)布局的列數(shù)來自動(dòng)適配的

修改 MainActivity.java

public class MainActivity extends AppCompatActivity {

    private List<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initFruits();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        FruitAdapter adapter = new FruitAdapter(fruitList);
        recyclerView.setAdapter(adapter);
    }
    private void initFruits() {
        for (int i = 0; i < 2; i++) {
            Fruit apple = new Fruit(getRandomLengthName("Apple"), R.drawable.apple_pic);
            fruitList.add(apple);
            Fruit banana = new Fruit(getRandomLengthName("Banana"), R.drawable.banana_pic);
            fruitList.add(banana);
            Fruit orange = new Fruit(getRandomLengthName("Orange"), R.drawable.orange_pic);
            fruitList.add(orange);
            Fruit watermelon = new Fruit(getRandomLengthName("Watermelon"), R.drawable.watermelon_pic);
            fruitList.add(watermelon);
            Fruit pear = new Fruit(getRandomLengthName("Pear"), R.drawable.pear_pic);
            fruitList.add(pear);
            Fruit grape = new Fruit(getRandomLengthName("Grape"), R.drawable.grape_pic);
            fruitList.add(grape);
            Fruit pineapple = new Fruit(getRandomLengthName("Pineapple"), R.drawable.pineapple_pic);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit(getRandomLengthName("Strawberry"), R.drawable.strawberry_pic);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit(getRandomLengthName("Cherry"), R.drawable.cherry_pic);
            fruitList.add(cherry);
            Fruit mango = new Fruit(getRandomLengthName("Mango"), R.drawable.mango_pic);
            fruitList.add(mango);
        }
    }
    private String getRandomLengthName(String name){
        Random random = new Random();
        int length= random.nextInt(20)+1;  // 產(chǎn)生1-20的隨機(jī)數(shù)
        StringBuilder builder = new StringBuilder();
        for (int i =0;i<length;i++){
            builder.append(name);
        }
        return  builder.function function toString() { [native code] }() { [native code] }();
    }
}

StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
StaggeredGridLayoutManager傳入2個(gè)參數(shù),第一個(gè)是布局的列數(shù),第二個(gè)是布局的排列方向。

random.nextInt(20)+1 產(chǎn)生1-20的隨機(jī)數(shù)
運(yùn)行效果:

image

GridLayoutManager和StaggeredGridLayout的區(qū)別

image
image

上圖是GridLayoutManager,下圖是StaggeredGridLayout憎蛤。
當(dāng)從顯示效果來看,已經(jīng)一目了然纪吮。
GridLayoutManager是會(huì)固定高度的,所以會(huì)留下很多空白區(qū)域蹂午。
相反,StaggeredGridLayout并不會(huì)固定高度,以至于就算子項(xiàng)的高度不一致,下一行的會(huì)自動(dòng)靠攏上一行。

RecyclerView 的點(diǎn)擊事件

修改 FruitAdapter.java

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

    private  List<Fruit> mFruitList;
    static class ViewHolder extends RecyclerView.ViewHolder{
        View fruitView;
        ImageView fruitImage;
        TextView fruitName;

        public ViewHolder (View view)
        {
            super(view);
            fruitView = view;
            fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
            fruitName = (TextView) view.findViewById(R.id.fruitname);
        }

    }

    public  FruitAdapter (List <Fruit> fruitList){
        mFruitList = fruitList;
    }

    @Override

    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fruit_item,parent,false);
        final ViewHolder holder = new ViewHolder(view);
        holder.fruitView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(view.getContext(), "you clicked view" + fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        holder.fruitImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int position = holder.getAdapterPosition();
                Fruit fruit = mFruitList.get(position);
                Toast.makeText(view.getContext(), "you clicked image" + fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return holder;
    }

  ...
}

修改ViewHolder,添加fruitView變量來保存子項(xiàng)最外層布局的實(shí)例。

運(yùn)行效果:


image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末巷疼,一起剝皮案震驚了整個(gè)濱河市晚胡,隨后出現(xiàn)的幾起案子灵奖,更是在濱河造成了極大的恐慌,老刑警劉巖瓷患,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件遣妥,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡爱态,警方通過查閱死者的電腦和手機(jī)境钟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來慨削,“玉大人,你說我怎么就攤上這事磁椒∶德” “怎么了?”我有些...
    開封第一講書人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵蘸拔,是天一觀的道長(zhǎng)环葵。 經(jīng)常有香客問我,道長(zhǎng)张遭,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任缔恳,我火速辦了婚禮洁闰,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘纸泄。我一直安慰自己,他們只是感情好聘裁,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著献起,像睡著了一般镣陕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上茁彭,一...
    開封第一講書人閱讀 52,156評(píng)論 1 308
  • 那天理肺,我揣著相機(jī)與錄音,去河邊找鬼善镰。 笑死,一個(gè)胖子當(dāng)著我的面吹牛乎完,可吹牛的內(nèi)容都是我干的品洛。 我是一名探鬼主播,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼帽揪,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了转晰?” 一聲冷哼從身側(cè)響起士飒,我...
    開封第一講書人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤酵幕,失蹤者是張志新(化名)和其女友劉穎扰藕,沒想到半個(gè)月后芳撒,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體他嫡,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡钢属,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年门躯,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片染乌。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡懂讯,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出勒庄,到底是詐尸還是另有隱情瘫里,我是刑警寧澤,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布局装,位于F島的核電站劳殖,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏哆姻。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一统舀、第九天 我趴在偏房一處隱蔽的房頂上張望劳景。 院中可真熱鬧,春花似錦闷串、人聲如沸筋量。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至琼梆,卻和暖如春窿吩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背纫雁。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工轧邪, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人闲勺。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓菜循,卻偏偏與公主長(zhǎng)得像申尤,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子昧穿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359

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