安卓高级3 RecyclerView 和cardView使用案例

cardView:

添加依赖:在Studio搜索cardview即可 在V7包中
或者直接在gradle中添加
compile 'com.android.support:cardview-v7:24.0.0'

cardView 完成一些绚丽特效使用:

属性:
app:cardElevation=”10dp”添加景深 (阴影效果让其更立体)
app:cardCornerRadius=”10dp”四边圆角值
app:cardBackgroundColor=”@android:color/holo_blue_ligh”背景色
android:foreground=”?android:attr/selectableItemBackground” 用户点击时会生成涟漪效果

<?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="10dp"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical"
    app:cardBackgroundColor="@android:color/holo_blue_light"
    app:cardCornerRadius="10dp"
    app:cardElevation="10dp">


    <TextView
        android:id="@+id/item_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="30dp"
        android:layout_marginTop="30dp"
        android:textColor="@android:color/white"
        android:textSize="20sp" />

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

效果图:
这里写图片描述


RecyclerView :

同样需要添加依赖 和上诉一样.

compile ‘com.android.support:recyclerview-v7:24.0.0’

可以实现GridView ListView 和流布局并且可以指定方向,和数据颠倒等

使用方法和适配器介绍:

  1. 在布局文件写入RecyclerView

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="qianfeng.com.day38_recyclerview.MainActivity">
    
    
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
    </RelativeLayout>
    
  2. 写布局管理器(多种) 和适配器:

    这里大家可以先不用管适配后面详解

    package qianfeng.com.day38_recyclerview;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.widget.Toast;
    
    import java.util.ArrayList;
    import java.util.List;
    
    
    /**java
     * RecyclerView:
     * 升级版的ListView   融合了  ListView  GridView  瀑布流    横纵向滑动
     * RecyclerView  使用  LayoutManager  进行布局管理
     * 1.LinearLayoutManager   线性布局管理器   -- > 横向或纵向的ListView展示效果
     * 2.GridLayoutManager    网格布局管理器 ---> 横向或纵向的 GridView 展示效果
     * 3.StraggXXXXXXXXXX    瀑布流
     *
     * LayoutManager
     * 实例化的时候 参数 上下文对象,横竖展示标记, 反转
     *
     * recyclerView 通过setLayoutManager()  方式 设置 布局管理器
     *
     * RecyclerAdapter
     * 是抽象类
     * 需要继承与  RecyclerView.Adapter<VH></>
     *
     * 传入的 ViewHodler 对象 必须继承与 RecyclerView.ViewHolder
     * 并重写 含有ItemView 的 构造方法
     *
     * 继承 RecyclerView.Adapter<VH></>类之后  需要重写三个方法
     * 1.getItemCount
     *      返回数据源的长度
     * 2.onCreateViewHolder
     *      实例化 itmeView
     *      并创建ViewHolder 对象 将其返回
     * 3.onBindViewHolder
     *      数据源 与ViewHolder 的持有View 进行绑定
     *
     * 设置监听器
     * RecyclerView 本身并不含有监听器  需要自己添加
     *
     * 在适配器中定义接口及方法
     * 给ItemView设置监听 并 对外暴露出接口
     * 由RecyclerView 进行监听 点击事件
     *
     * 获取ItemView 的position
     * RecyclerView .getChildAdapterPosition(ItemView)
     *
     *
     * RecyclerView 没有分割线属性
     * 不推荐使用
     * LinearLayoutmanager  纵向模式下
     * 可以使用 DividerItemDecoration  进行 分割线修改
     *
     * recyclerView.addItemDecoration();  添加分割线属性
     *
     *  value  -- style
     *  添加一个    android:listDivider 属性
     *  值  添加  shape 或者 图片  作为分割线展示
     *  如果只添加颜色 则 没有高度  无法展示
     *
     * 推荐使用的:(不需要分割线)
     *
     * CardView
     *
     *
     */
    public class MainActivity extends AppCompatActivity implements MyRecyclerAdapter.OnItemClickListener {
    
        private RecyclerView recyclerView;
        private List<String> list = new ArrayList<>();
        private MyRecyclerAdapter myRecyclerAdapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            // 实例化RecyclerView 对象
            recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    
            /**
             *  上下文对象
             *  方向
             *  是否反转
             *  如果翻转 数据颠倒并且进入界面时跳到最后显示第一个item(相当于正向的第一个数据item)
             *  如果方向是横向LinearLayoutManager.HORIZONTAL 那么整个activity只显示一个item,向右滑动即可显示下一个item和Viewpager相识
             */
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
    //        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4, LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(linearLayoutManager);
            // 添加自定义的   分割线 (不推荐)
            recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
            initData();
            // 设置适配器
            myRecyclerAdapter = new MyRecyclerAdapter(list, this, recyclerView, this);
            recyclerView.setAdapter(myRecyclerAdapter);
        }
    
        private void initData() {
            for (int i = 0; i < 50; i++) {
                list.add("哈哈哈哈" + i);
            }
        }
        //以下监听为我们在适配器中添加的
      @Override
    public void onItemClickListener(int position) {
        Toast.makeText(MainActivity.this, "点击————" + position, Toast.LENGTH_LONG).show();
    }
    
    @Override
    public void onItemLongClickListener(int position) {
        Toast.makeText(MainActivity.this, "长按————" + position, Toast.LENGTH_LONG).show();
    }
    
    }
    

    效果图:
    这里写图片描述

    如果上诉案例写成竖直方向:

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    效果图
    

    这里写图片描述

    • 反向:大家可以自己试试:这里直接说结果,上诉竖直方向会直接滑到哈哈0 (此时哈哈0是在列表底部的注意)

    上诉案例:用改用gridlayout

    //没行4个
    GridLayoutManager(this, 4, LinearLayoutManager.HORIZONTAL, false);
            recyclerView.setLayoutManager(gridLayoutManager);

    效果图:
    这里写图片描述
    另一个方向参考上一个Linear案例

    适配器

package qianfeng.com.day38_recyclerview;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by ${Mr.Zhao} on 2016/10/19.
 */
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {


    List<String> list;
    Context context;
    LayoutInflater inflater;
    RecyclerView recyclerView;

    private OnItemClickListener listener;

    public interface OnItemClickListener {
        public void onItemClickListener(int position);

        public void onItemLongClickListener(int position);

    }


    public MyRecyclerAdapter(List<String> list, Context context, RecyclerView recyclerView, OnItemClickListener listener) {
        this.list = list;
        this.context = context;
        this.recyclerView = recyclerView;
        inflater = LayoutInflater.from(context);
        this.listener = listener;
    }

    // 该方法为 创建ViewHolder 使用
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //  实例化  itemView
        View view = inflater.inflate(R.layout.item_layout, parent, false);
        return new MyViewHolder(view);
    }

    //  该方法为  绑定数据使用
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        holder.item_tv.setText(list.get(position));
    }

    // 返回数据长度
    @Override
    public int getItemCount() {
        return list.size();
    }

    // 定义  ViewHolder
    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView item_tv;

        // 必须实现的有参构造
        public MyViewHolder(final View itemView) {
            super(itemView);
            //   实例化 textView
            item_tv = ((TextView) itemView.findViewById(R.id.item_tv));

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //   获取itemView 的 位置
                    int childPosition = recyclerView.getChildAdapterPosition(itemView);
                    // 监听方法
                    listener.onItemClickListener(childPosition);
                }
            });

            itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int childAdapterPosition = recyclerView.getChildAdapterPosition(itemView);
                    listener.onItemLongClickListener(childAdapterPosition);
                    return true;
                }
            });
        }
    }
}
  • 一个分割线类
package qianfeng.com.day38_recyclerview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 *   ListView 模式 下的  下划线
 * Created by ${Mr.Zhao} on 2016/5/26.
 *
 *  可以自由更改分割线   android.R.attr.listDivider
 *  去  values  的 styles   下 添加 android:listDivider  属性  在面的值 可以任意修改
 *  图片或者颜色 或者 Drawable 资源
 */
public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{
            android.R.attr.listDivider
    };

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

    private Drawable mDivider;

    private int mOrientation;

    public DividerItemDecoration(Context context, int orientation) {
        final TypedArray a = context.obtainStyledAttributes(ATTRS);
        mDivider = a.getDrawable(0);
        a.recycle();
        setOrientation(orientation);
    }

    public void setOrientation(int orientation) {
        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {
            throw new IllegalArgumentException("invalid orientation");
        }
        mOrientation = orientation;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent) {

        if (mOrientation == VERTICAL_LIST) {
            drawVertical(c, parent);
        } else {
            drawHorizontal(c, parent);
        }

    }


    public void drawVertical(Canvas c, RecyclerView parent) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            RecyclerView v = new RecyclerView(parent.getContext());
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int top = child.getBottom() + params.bottomMargin;
            final int bottom = top + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    public void drawHorizontal(Canvas c, RecyclerView parent) {
        final int top = parent.getPaddingTop();
        final int bottom = parent.getHeight() - parent.getPaddingBottom();

        final int childCount = parent.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final View child = parent.getChildAt(i);
            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                    .getLayoutParams();
            final int left = child.getRight() + params.rightMargin;
            final int right = left + mDivider.getIntrinsicHeight();
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
        if (mOrientation == VERTICAL_LIST) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        } else {
            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
        }
    }

}

多布局

适配器中有多个viewhold然后根据 返回类型确定用哪个viewhold

package com.example.administrator.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends AppCompatActivity {


    private RecyclerView recyclerView;
    private GridLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
        linearLayoutManager = new GridLayoutManager(this,3,GridLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(linearLayoutManager);
        Myadapter myadapter = new Myadapter();
        recyclerView.setAdapter(myadapter);
        //找到第一个显示的位置
        linearLayoutManager.findFirstVisibleItemPosition();
        //找到最后一个显示的位置
        linearLayoutManager.findLastVisibleItemPosition();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.e("tag", linearLayoutManager.findFirstVisibleItemPosition()+"");
                }
            }
        }.start();
    }

    class  Myadapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{


        class MyViewHold extends RecyclerView.ViewHolder{

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

        class MyViewHold2 extends RecyclerView.ViewHolder{

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

        //自定义一个返回类型实现多布局
        @Override
        public int getItemViewType(int position) {

            return super.getItemViewType(position);

        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View inflate = getLayoutInflater().inflate(R.layout.item, parent, false);
            MyViewHold2 myViewHold2= new MyViewHold2(inflate) ;


            //这里可以自定义适配器viewhold实现多布局
           /* switch (viewType){
                default:
            }*/

            return myViewHold2;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof  MyViewHold2){

            }else if (holder instanceof MyViewHold){

            }
        }

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

}

posted on 2016-10-20 11:51  木鱼哥  阅读(304)  评论(0编辑  收藏  举报

导航