博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
RecyclerView
阅读量:6256 次
发布时间:2019-06-22

本文共 18692 字,大约阅读时间需要 62 分钟。

话说RecyclerView已经出生非常长时间了特点和ListView,GridView类似。

长处是:(使用更加灵活、item能够直接使用动画等..)那么今天開始我们来重点学习一下RecyclerView控件。以下直接上代码:

1. 创建一个新项目

1.在Android studio中,通过 File ⇒ New Project
2.加入依赖 
  
build.gradledependencies {compile fileTree(dir: 'libs', include: ['*.jar'])testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:23.1.1'compile 'com.android.support:design:23.1.1'compile 'com.android.support:recyclerview-v7:23.1.1'}
3.默认会有两个文件activity_main.xml(CoordinatorLayout、AppBarLayout)和content_main.xml(项目用到的内容)
content_main.xml

xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main" <div style="text-align: left;"></div>tools:context=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="vertical" /> </RelativeLayout>

4.打开colors.xml位置在res ⇒ values

colors.xml

> <resources> <color name="colorPrimary">#3F51B5</color> <color name="colorPrimaryDark">#303F9F</color> <color name="colorAccent">#FF4081</color> <color name="year">#999999</color> <color name="title">#222222</color> </resources>

2.写适配器

5.自己定义一个实体类
Movie.javapackage info.androidhive.recyclerview;public class Movie {private String title, genre, year;public Movie() {}public Movie(String title, String genre, String year) {this.title = title;this.genre = genre;this.year = year;}public String getTitle() {return title;}public void setTitle(String name) {this.title = name;}public String getYear() {return year;}public void setYear(String year) {this.year = year;}public String getGenre() {return genre;}public void setGenre(String genre) {this.genre = genre;}}
6.创建一个
movie_list_row.xml
在Layout文件夹。
这个文件用于在RecyclerView中显示用到的item
movie_list_row.xml

xml version="1.0" encoding="utf-8"?

> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:focusable="true" android:paddingLeft="16dp" android:paddingRight="16dp" android:paddingTop="10dp" android:paddingBottom="10dp" android:clickable="true" android:background="?android:attr/selectableItemBackground" android:orientation="vertical"> <TextView android:id="@+id/title" android:textColor="@color/title" android:textSize="16dp" android:textStyle="bold" android:layout_alignParentTop="true" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/genre" android:layout_below="@id/title" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/year" android:textColor="@color/year" android:layout_width="wrap_content" android:layout_alignParentRight="true" android:layout_height="wrap_content" /> </RelativeLayout>

7.如今创建类MoviesAdapter加入下面代码。

HereonCreateViewHolder()方法用于载入movie_list_row.xml.在onBindViewHolder()为了适配数据(title, genre和year)

MoviesAdapter.javapackage info.androidhive.recyclerview;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;public class MoviesAdapter extends RecyclerView.Adapter
{private List
moviesList;public class MyViewHolder extends RecyclerView.ViewHolder {public TextView title, year, genre;public MyViewHolder(View view) {super(view);title = (TextView) view.findViewById(R.id.title);genre = (TextView) view.findViewById(R.id.genre);year = (TextView) view.findViewById(R.id.year);}}public MoviesAdapter(List
moviesList) {this.moviesList = moviesList;}@Overridepublic MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.movie_list_row, parent, false);return new MyViewHolder(itemView);}@Overridepublic void onBindViewHolder(MyViewHolder holder, int position) {Movie movie = moviesList.get(position);holder.title.setText(movie.getTitle());holder.genre.setText(movie.getGenre());holder.year.setText(movie.getYear());}@Overridepublic int getItemCount() {return moviesList.size();}}
8.打开
MainActivity
做下面改变,
prepareMovieData()这种方法
加入了一些数据在列表中.
MainActivity.javapackage info.androidhive.recyclerview;import android.content.Context;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.DefaultItemAnimator;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.Toolbar;import android.view.GestureDetector;import android.view.MotionEvent;import android.view.View;import android.widget.Toast;import java.util.ArrayList;import java.util.List;public class MainActivity extends AppCompatActivity {private List
movieList = new ArrayList<>();private RecyclerView recyclerView;private MoviesAdapter mAdapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);setSupportActionBar(toolbar);recyclerView = (RecyclerView) findViewById(R.id.recycler_view);mAdapter = new MoviesAdapter(movieList);RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());recyclerView.setLayoutManager(mLayoutManager);recyclerView.setItemAnimator(new DefaultItemAnimator());recyclerView.setAdapter(mAdapter);prepareMovieData();}private void prepareMovieData() {Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015");movieList.add(movie);movie = new Movie("Inside Out", "Animation, Kids & Family", "2015");movieList.add(movie);movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015");movieList.add(movie);movie = new Movie("Shaun the Sheep", "Animation", "2015");movieList.add(movie);movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015");movieList.add(movie);movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015");movieList.add(movie);movie = new Movie("Up", "Animation", "2009");movieList.add(movie);movie = new Movie("Star Trek", "Science Fiction", "2009");movieList.add(movie);movie = new Movie("The LEGO Movie", "Animation", "2014");movieList.add(movie);movie = new Movie("Iron Man", "Action & Adventure", "2008");movieList.add(movie);movie = new Movie("Aliens", "Science Fiction", "1986");movieList.add(movie);movie = new Movie("Chicken Run", "Animation", "2000");movieList.add(movie);movie = new Movie("Back to the Future", "Science Fiction", "1985");movieList.add(movie);movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981");movieList.add(movie);movie = new Movie("Goldfinger", "Action & Adventure", "1965");movieList.add(movie);movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014");movieList.add(movie);mAdapter.notifyDataSetChanged();}}
 
这是我的执行结果:

3.给你的RecyclerView加入切割线

 
9.
创建DividerItemDecoration
DividerItemDecoration.javapackage info.androidhive.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; /** * Created by Lincoln on 30/10/15. */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 onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {        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);            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, View view, RecyclerView parent, RecyclerView.State state) {        if (mOrientation == VERTICAL_LIST) {            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());        } else {            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);        }    }}
10.
打开MainActivity通过addItemDecoration()方法为item加入切割线
recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); // set the adapterrecyclerView.setAdapter(mAdapter);
 我的App执行结果是:
 
4.为RecyclerView Item 加入点击事件
RecyclerView 默认没有OnItemClickListener方法。我们须要自己写;
11
.在
MainActivity加入RecyclerTouchListener类,ClickListener接口
MainActivity.javapublic interface ClickListener {        void onClick(View view, int position);         void onLongClick(View view, int position);    }     public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {         private GestureDetector gestureDetector;        private MainActivity.ClickListener clickListener;         public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {            this.clickListener = clickListener;            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {                @Override                public boolean onSingleTapUp(MotionEvent e) {                    return true;                }                 @Override                public void onLongPress(MotionEvent e) {                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());                    if (child != null && clickListener != null) {                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));                    }                }            });        }         @Override        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {             View child = rv.findChildViewUnder(e.getX(), e.getY());            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {                clickListener.onClick(child, rv.getChildPosition(child));            }            return false;        }         @Override        public void onTouchEvent(RecyclerView rv, MotionEvent e) {        }         @Override        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {         }    }
 
最后为RecyClerView加入监听
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() {            @Override            public void onClick(View view, int position) {                Movie movie = movieList.get(position);                Toast.makeText(getApplicationContext(), movie.getTitle() + " is selected!", Toast.LENGTH_SHORT).show();            }             @Override            public void onLongClick(View view, int position) {             }        }));

如今你能够验证点击事件了,我的执行结果:

最后贴出Activity全部代码:

package info.androidhive.recyclerview; import android.content.Context;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.support.v7.widget.DefaultItemAnimator;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.support.v7.widget.Toolbar;import android.view.GestureDetector;import android.view.MotionEvent;import android.view.View;import android.widget.Toast; import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity {    private List
movieList = new ArrayList<>(); private RecyclerView recyclerView; private MoviesAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); mAdapter = new MoviesAdapter(movieList); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new ClickListener() { @Override public void onClick(View view, int position) { Movie movie = movieList.get(position); Toast.makeText(getApplicationContext(), movie.getTitle() + " is selected!", Toast.LENGTH_SHORT).show(); } @Override public void onLongClick(View view, int position) { } })); prepareMovieData(); } private void prepareMovieData() { Movie movie = new Movie("Mad Max: Fury Road", "Action & Adventure", "2015"); movieList.add(movie); movie = new Movie("Inside Out", "Animation, Kids & Family", "2015"); movieList.add(movie); movie = new Movie("Star Wars: Episode VII - The Force Awakens", "Action", "2015"); movieList.add(movie); movie = new Movie("Shaun the Sheep", "Animation", "2015"); movieList.add(movie); movie = new Movie("The Martian", "Science Fiction & Fantasy", "2015"); movieList.add(movie); movie = new Movie("Mission: Impossible Rogue Nation", "Action", "2015"); movieList.add(movie); movie = new Movie("Up", "Animation", "2009"); movieList.add(movie); movie = new Movie("Star Trek", "Science Fiction", "2009"); movieList.add(movie); movie = new Movie("The LEGO Movie", "Animation", "2014"); movieList.add(movie); movie = new Movie("Iron Man", "Action & Adventure", "2008"); movieList.add(movie); movie = new Movie("Aliens", "Science Fiction", "1986"); movieList.add(movie); movie = new Movie("Chicken Run", "Animation", "2000"); movieList.add(movie); movie = new Movie("Back to the Future", "Science Fiction", "1985"); movieList.add(movie); movie = new Movie("Raiders of the Lost Ark", "Action & Adventure", "1981"); movieList.add(movie); movie = new Movie("Goldfinger", "Action & Adventure", "1965"); movieList.add(movie); movie = new Movie("Guardians of the Galaxy", "Science Fiction & Fantasy", "2014"); movieList.add(movie); mAdapter.notifyDataSetChanged(); } public interface ClickListener { void onClick(View view, int position); void onLongClick(View view, int position); } public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener { private GestureDetector gestureDetector; private MainActivity.ClickListener clickListener; public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) { this.clickListener = clickListener; gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public void onLongPress(MotionEvent e) { View child = recyclerView.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null) { clickListener.onLongClick(child, recyclerView.getChildPosition(child)); } } }); } @Override public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { View child = rv.findChildViewUnder(e.getX(), e.getY()); if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) { clickListener.onClick(child, rv.getChildPosition(child)); } return false; } @Override public void onTouchEvent(RecyclerView rv, MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } } }

转载地址:http://ietsa.baihongyu.com/

你可能感兴趣的文章
django和apache交互的wsgi分析
查看>>
python --- json模块和pickle模块详解
查看>>
说说一道实在很多陷阱的题
查看>>
EM算法
查看>>
jzoj p1306 河流
查看>>
关于JSBuilder2的使用.
查看>>
iPhone4S、iPad2即将完美越狱
查看>>
18windows_18_scrollBar滚动条
查看>>
本地推送
查看>>
Beta 冲刺 (7/7)
查看>>
区块链实现简单的电商交易(以太坊)
查看>>
VMware报错:"激活连接失败:No suitable device found for this connection."
查看>>
maven设置
查看>>
个人考场VIM配置
查看>>
adobe
查看>>
微信小程序中的分享事件
查看>>
HDU 6069 Counting Divisors【区间素筛】【经典题】【好题】
查看>>
使用HAXM为QEMU for Windows加速
查看>>
配置tomcat下war包可以自压缩
查看>>
idea中artifacts、facets、modules是什么意思?
查看>>