Android RecyclerView初探

使用RecyclerView列表,由于RecyclerView也是属于MD风格中的控件所以也需要添加依赖
compile ‘com.android.support:design:26.+’ //导入md风格依赖包

实现列表需要有适配器和item
以下是item的布局文件.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView

    android:layout_width="match_parent"
    android:layout_height="120dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_below="@+id/toolbar"
    android:id="@+id/cardview"
    android:layout_margin="10dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="10dp"

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

        <ImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/logo"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            >
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="这是一个CardView"
                android:textColor="@android:color/black"
                android:textSize="20dp"/>
        </LinearLayout>

    </RelativeLayout>


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

主要代码

   mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        MyAdapter myAdapter = new MyAdapter();
        //设置列表的布局(这里是垂直线性布局)
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(myAdapter);

注意记得设置setLayoutManger,否则会无法显示列表

以下是适配器MyAdapter代码

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHodler>{


        @Override
        public MyViewHodler onCreateViewHolder(ViewGroup parent, int viewType) {

            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.card_item,parent,false);
            return new MyViewHodler(view);
        }

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

        }

        @Override
        public int getItemCount() {
            return 10;
        }

        public class MyViewHodler extends RecyclerView.ViewHolder{

            public MyViewHodler(View itemView) {
                super(itemView);
            }
        }
    }

MyAdapter继承至RecyclerView.Adapter<>,必须重写onCreateViewHolder()、onBindViewHolder()、getItemCount()方法 有点类似ListView

效果图
这里写图片描述

作者:郑权
原文链接:点击这里

猜你喜欢

转载自blog.csdn.net/fjnu_se/article/details/80779931
今日推荐