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

效果图
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值