RecyclerView 사용 상세 설명

24266 단어 RecyclerView
RecylerView 소개
RecylerView 는 슈퍼 port-v7 패키지 의 새로운 구성 요소 로 강력 한 미끄럼 구성 요소 입 니 다.전형 적 인 ListView 에 비해 item 재 활용 기능 이 있 습 니 다.이 점 은 recylerview 즉 재 활용 view 라 는 이름 에서 도 알 수 있 습 니 다.공식 적 으로 그 에 대한 소 개 는 RecyclerView 는 ListView 의 업그레이드 버 전 으로 더욱 선진 적 이 고 유연 하 다 는 것 이다.RecyclerView 는 LayoutManager,ItemDecoration,ItemAnimator 를 설정 하여 원 하 는 효 과 를 실현 합 니 다.
  • LayoutManager 를 사용 하여 모든 item 의 배열 방식 을 확인 합 니 다
  • ItemDecoration 을 사용 하여 스스로 분할 선 을 그립 니 다.더욱 유연 합 니 다
  • ItemAnimator 를 사용 하여 애니메이션 효 과 를 추가 하거나 삭제 합 니 다
  • 주의 하 다.
    새 항목 을 만 들 려 면 app/build.gradle 에 RecylerView 의존 도 를 늘 려 야 합 니 다.그렇지 않 으 면 RecyclerView 클래스 를 찾 을 수 없습니다.compile 'com.android.support:recyclerview-v7:23.1.0'RecylerView 간단 한 데모.
    activity 코드 를 보 겠 습 니 다.ListView 와 쓰기 차이 가 많 지 않 습 니 다.다만 여기 레이아웃 관리 자 를 많이 설 치 했 습 니 다.
    
    public class LinearLayoutActivity extends AppCompatActivity {
     private RecyclerView recyclerView;
     private RecyclerViewAdapter adapter;
     private List<String> datas;
     @Override
     public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.recycler_main);
     initData();
     recyclerView= (RecyclerView) findViewById(R.id.recyclerview);
     recyclerView.setLayoutManager(new LinearLayoutManager(this));//       
     recyclerView.addItemDecoration(new DividerItemDecoration(this));
     recyclerView.setAdapter(adapter=new RecyclerViewAdapter(this,datas));
     }
     private void initData(){
     datas=new ArrayList<>();
     for(int i=0;i<100;i++){
      datas.add("item:"+i);
     }
     }
    }
    
    activity 에 대응 하 는 레이아웃 파일:recyclermain.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="match_parent">
     <android.support.v7.widget.RecyclerView
     android:id="@+id/recyclerview"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />
    </RelativeLayout>
    
    adapter 는 ListView 에 비해 변화 가 크다.View Holder 논 리 를 봉 하여 코드 가 상대 적 으로 간단 하 다.
  • RecyclerView.Adapter 를 계승 하고 세 가지 방법 을 다시 써 야 합 니 다
  • MyViewHolder 는 RecyclerView 를 계승 해 야 합 니 다.ViewHolder
    
    public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{
    private List<String> datas;
    private LayoutInflater inflater;
    public RecyclerViewAdapter(Context context,List<String> datas){
     inflater=LayoutInflater.from(context);
     this.datas=datas;
    }
    //      View  RecyclerView.ViewHolder  
    @Override
    public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
     View itemView=inflater.inflate(R.layout.recycler_item,null);
     return new MyViewHolder(itemView);
    }
    //    View    
    @Override
    public void onBindViewHolder(RecyclerViewAdapter.MyViewHolder holder, int position) {
     holder.textview.setText(datas.get(position));
    }
    //      
    @Override
    public int getItemCount() {
     return datas.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder{
     private TextView textview;
    
     public MyViewHolder(View itemView) {
     super(itemView);
     textview= (TextView) itemView.findViewById(R.id.textview);
     }
    }
    }
    
    효과 도 를 살 펴 보 자.
     
    RecyclerView 구분자 증가
    RecyclerView 는 android:divider 와 android:divider Height 속성 이 없습니다.만약 에 우리 가 분할 선 을 필요 로 한다 면 스스로 실현 할 수 밖 에 없습니다.
  • ItemDecoration 류 를 계승 하여 onDraw 와 getItemOffsets 방법 을 실현 해 야 합 니 다
  • RecyclerView 의 addItemDecoration 방법 을 호출 합 니 다
  • DividerItemDecoration 클래스 를 작성 하고 RecyclerView 를 계승 합 니 다.ItemDecoration 은 getItemOffsets 에서 item 사이 의 간격 을 두 고 onDraw 방법 으로 그립 니 다.(onDraw 의 그리 기 는 줄 마다 우선 합 니 다)
    
    public class DividerItemDecoration extends RecyclerView.ItemDecoration{
     /*
     * RecyclerView     ,           
     * RecyclerView      ,    
     *                 
     * */
     private int mOrientation = LinearLayoutManager.VERTICAL;
     private int mItemSize = 1;//item      size,   1
     private Paint mPaint;//  item      ,      
     public DividerItemDecoration(Context context) {
     this(context,LinearLayoutManager.VERTICAL,R.color.colorAccent);
     }
     public DividerItemDecoration(Context context, int orientation) {
     this(context,orientation, R.color.colorAccent);
     }
     public DividerItemDecoration(Context context, int orientation, int dividerColor){
     this(context,orientation,dividerColor,1);
     }
     /**
     * @param context
     * @param orientation     
     * @param dividerColor           id
     * @param mItemSize         dp   
     */
     public DividerItemDecoration(Context context, int orientation, int dividerColor, int mItemSize){
     this.mOrientation = orientation;
     if(orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL){
      throw new IllegalArgumentException("        ") ;
     }
     // dp    px
     this.mItemSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,mItemSize,context.getResources().getDisplayMetrics());
     mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
     mPaint.setColor(context.getResources().getColor(dividerColor));
     }
     @Override
     public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
     if(mOrientation == LinearLayoutManager.VERTICAL){
      drawVertical(c,parent) ;
     }else {
      drawHorizontal(c,parent) ;
     }
     }
     /**
     *      item    
     * @param canvas
     * @param parent
     */
     private void drawVertical(Canvas canvas,RecyclerView parent){
     final int left = parent.getPaddingLeft() ;
     final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
     final int childSize = parent.getChildCount() ;
     for(int i = 0 ; i < childSize ; i ++){
      final View child = parent.getChildAt( i ) ;
      RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
      final int top = child.getBottom() + layoutParams.bottomMargin ;
      final int bottom = top + mItemSize ;
      canvas.drawRect(left,top,right,bottom,mPaint);
     }
     }
     /**
     *      item    
     * @param canvas
     * @param parent
     */
     private void drawHorizontal(Canvas canvas,RecyclerView parent){
     final int top = parent.getPaddingTop() ;
     final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom() ;
     final int childSize = parent.getChildCount() ;
     for(int i = 0 ; i < childSize ; i ++){
      final View child = parent.getChildAt( i ) ;
      RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
      final int left = child.getRight() + layoutParams.rightMargin ;
      final int right = left + mItemSize ;
      canvas.drawRect(left,top,right,bottom,mPaint);
     }
     }
     /**
     *   item    size
     * @param outRect
     * @param view
     * @param parent
     * @param state
     */
     @Override
     public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
     if(mOrientation == LinearLayoutManager.VERTICAL){
      outRect.set(0,0,0,mItemSize);//         
     }else {
      outRect.set(0,0,mItemSize,0);//         
     }
     }
    }
    
    addItemDecoration 방법 을 사용 하 는 것 을 잊 지 마 세 요.recyclerView.addItemDecoration(new DividerItemDecoration(this));// 다시 실행,효과 그림:

    여기까지 읽 으 시 면 분명 의문 이 있 을 겁 니 다.이 물건 은 ListView 보다 훨씬 번 거 롭 습 니 다.그런데 구 글 공식 적 으로 왜 ListView 의 업그레이드 버 전이 라 고 말 합 니까?이제 확대 기 를 시작 하 겠 습 니 다...
    GridLayoutManager
    RecyclerView 에서 서로 다른 목록 을 구현 하려 면 LayoutManager 를 바 꾸 기만 하면 됩 니 다.RecyclerView.LayoutManager 는 RecyclerView.ItemDecoration 과 마찬가지 로 RecyclerView 정적 추상 내부 클래스 이지 만 LayoutManager 는 세 가지 공식 적 으로 작성 한 실현 클래스 가 있 습 니 다.
    선형 레이아웃 관리자 와 ListView 기능 이 비슷 하 다GridLayoutManager 격자 레이아웃 관리자 와 GridView 기능 이 비슷 합 니 다Staggered GridLayoutManager 폭포 흐름 레이아웃 관리자방금 우리 가 사용 한 것 은 LinearLayoutManager 입 니 다.지금 우 리 는 GridLayoutManager 로 전환 합 니 다.아래 코드 를 보 니 분 단위 로 다른 목록 을 전환 하 는 느낌 이 들 지 않 습 니까?recyclerView.setLayoutManager(new GridLayoutManager(this,2));여러 열 을 표시 하거나 세로 로 표시 하려 면 new 의 서로 다른 구조 방법 으로 다음 코드 는 세로 로 4 열 을 표시 합 니 다.현재 반대 방향 표시 가 필요 하 다 면 false 를 true 로 바 꾸 면 됩 니 다.recyclerView.setLayoutManager(new GridLayoutManager(this,4,GridLayoutManager.HORIZONTAL,false));격자 레이아웃 을 사용 하기 때문에 분할 선 을 그 리 는 코드 는 다시 수정 해 야 합 니 다.격자 레이아웃 한 줄 에 여러 열 이 있 을 수 있 고 마지막 열 과 마지막 줄 은 그 릴 필요 가 없 기 때문에 클래스 를 다시 만들어 야 합 니 다.
    DividerGridItemDecoration.java
    
    public class DividerGridItemDecoration extends RecyclerView.ItemDecoration {
     /*
     * RecyclerView     ,           
     * RecyclerView      ,    
     *                 
     * */
     private int mOrientation = LinearLayoutManager.VERTICAL;
     private int mItemSize = 1;//item      size,   1
     private Paint mPaint;//  item      ,      
     public DividerGridItemDecoration(Context context) {
     this(context,LinearLayoutManager.VERTICAL,R.color.colorAccent);
     }
     public DividerGridItemDecoration(Context context, int orientation) {
     this(context,orientation, R.color.colorAccent);
     }
     public DividerGridItemDecoration(Context context, int orientation, int dividerColor){
     this(context,orientation,dividerColor,1);
     }
     /**
     * @param context
     * @param orientation     
     * @param dividerColor           id
     * @param mItemSize         dp   
     */
     public DividerGridItemDecoration(Context context, int orientation, int dividerColor, int mItemSize){
     this.mOrientation = orientation;
     if(orientation != LinearLayoutManager.VERTICAL && orientation != LinearLayoutManager.HORIZONTAL){
      throw new IllegalArgumentException("        ") ;
     }
     // dp    px
     this.mItemSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,mItemSize,context.getResources().getDisplayMetrics());
     mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
     mPaint.setColor(context.getResources().getColor(dividerColor));
     }
     @Override
     public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
     drawHorizontal(c, parent);
     drawVertical(c, parent);
     }
     private int getSpanCount(RecyclerView parent) {
     //   
     int spanCount = -1;
     RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
     if (layoutManager instanceof GridLayoutManager) {
      spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
     } else if (layoutManager instanceof StaggeredGridLayoutManager) {
      spanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
     }
     return spanCount;
     }
     public void drawHorizontal(Canvas canvas, RecyclerView parent) {
     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.getLeft() - params.leftMargin;
      final int right = child.getRight() + params.rightMargin + mItemSize;
      final int top = child.getBottom() + params.bottomMargin;
      final int bottom = top + mItemSize;
      canvas.drawRect(left,top,right,bottom,mPaint);
     }
     }
     public void drawVertical(Canvas canvas, RecyclerView parent) {
     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.getTop() - params.topMargin;
      final int bottom = child.getBottom() + params.bottomMargin;
      final int left = child.getRight() + params.rightMargin;
      final int right = left + mItemSize;
      canvas.drawRect(left,top,right,bottom,mPaint);
     }
     }
     @Override
     public void getItemOffsets(Rect outRect, int itemPosition,RecyclerView parent) {
     int spanCount = getSpanCount(parent);
     int childCount = parent.getAdapter().getItemCount();
     if (isLastRow(parent, itemPosition, spanCount, childCount)){//       ,       
      outRect.set(0, 0, mItemSize, 0);
     } else if (isLastColum(parent, itemPosition, spanCount, childCount)){//        ,       
      outRect.set(0, 0, 0, mItemSize);
     } else {
      outRect.set(0, 0, mItemSize,mItemSize);
     }
     }
     private boolean isLastColum(RecyclerView parent, int pos, int spanCount, int childCount) {
     RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
     if (layoutManager instanceof GridLayoutManager) {
      if ((pos + 1) % spanCount == 0){//        ,        
      return true;
      }
     } else if (layoutManager instanceof StaggeredGridLayoutManager) {
      int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
      if (orientation == StaggeredGridLayoutManager.VERTICAL) {
      if ((pos + 1) % spanCount == 0){//        ,        
       return true;
      }
      } else {
      childCount = childCount - childCount % spanCount;
      if (pos >= childCount)//        ,        
       return true;
      }
     }
     return false;
     }
     private boolean isLastRow(RecyclerView parent, int pos, int spanCount, int childCount) {
     RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
     if (layoutManager instanceof GridLayoutManager) {
      childCount = childCount - childCount % spanCount;
      if (pos >= childCount)//    
      return true;
     } else if (layoutManager instanceof StaggeredGridLayoutManager) {
      int orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
      if (orientation == StaggeredGridLayoutManager.VERTICAL){//  
      childCount = childCount - childCount % spanCount;
      if (pos >= childCount)//    
       return true;
      } else{ //  
      if ((pos + 1) % spanCount == 0) {//     
       return true;
      }
      }
     }
     return false;
     }
    }
    
    이 두 개의 분할 선 을 그 리 는 클래스 를 썼 습 니 다.주류 의 레이아웃:선형 목록 과 격자 목록 을 모두 보 여 줍 니 다.빨리 코드 를 실행 해서 결 과 를 보십시오.
     
    StaggeredGridLayoutManager
    actviity 에서 레이아웃 관리 자 를 수정 하면 익숙 해 지 실 거 예요~~~
    
    recyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL));
    폭포 흐름 목록 의 일반 열 높이 는 일치 하지 않 습 니 다.서로 다른 너비 와 높이 를 모 의 하기 위해 데이터 원본 은 String 형식 을 대상 으로 바 꾸 었 습 니 다.그리고 초기 화 할 때 무 작위 로 높이 를 만 들 었 습 니 다.
    
    public class ItemData {
     private String content;//item  
     private int height;//item  
     public ItemData() {
     }
     public ItemData(String content, int height) {
     this.content = content;
     this.height = height;
     }
     public String getContent() {
     return content;
     }
     public void setContent(String content) {
     this.content = content;
     }
     public int getHeight() {
     return height;
     }
     public void setHeight(int height) {
     this.height = height;
     }
    }
    
    폭포 흐름 목록 에 분할 선 을 추가 하지 않 고 item 레이아웃 에 android:padding 속성 을 설정 하 였 습 니 다.recycler_staggered_item.xml
    
    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:padding="5dp"
     android:layout_width="wrap_content"
     android:layout_height="match_parent">
     <TextView
     android:id="@+id/textview"
     android:background="@color/colorAccent"
     android:layout_width="100dp"
     android:layout_height="wrap_content"
     android:gravity="center"
     android:text="122"
     android:textSize="20sp"/>
    </FrameLayout>
    
    마지막 으로 어댑터 의 onBindView Holder 방법 에서 itemd 의 TextView 에 높이 를 설정 합 니 다.
    
    @Override
    public void onBindViewHolder(StaggeredGridAdapter.MyViewHolder holder, int position) {
     ItemData itemData=datas.get(position);
     holder.textview.setText(itemData.getContent());
     //      ,           
     holder.textview.setHeight(itemData.getHeight());
    }
    so easy 느낌 인지 빨리 실행 해 보 세 요.효과:

    header 와 footer 추가
    RecyclerView 에 머리 와 밑부분 을 추가 하 는 것 은 대응 하 는 api 가 없 지만 우리 의 많은 수요 가 사용 되 기 때문에 스스로 방법 을 강구 하여 실현 할 수 밖 에 없다.우 리 는 어댑터 의 getItemView Type 방법 을 통 해 이 기능 을 실현 할 수 있다.
    수 정 된 어댑터 코드:RecyclerHead FootView Adapter.java
    
    public class RecyclerHeadFootViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
     private List<String> datas;
     private LayoutInflater inflater;
     public static final int TYPE_HEADER=1;//header  
     public static final int TYPE_FOOTER=2;//footer  
     private View header=null;// View
     private View footer=null;// View
     public RecyclerHeadFootViewAdapter(Context context, List<String> datas){
     inflater=LayoutInflater.from(context);
     this.datas=datas;
     }
     //      View  RecyclerView.ViewHolder  
     @Override
     public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
     if(viewType==TYPE_HEADER){
      return new RecyclerView.ViewHolder(header){};
     }else if(viewType==TYPE_FOOTER){
      return new RecyclerView.ViewHolder(footer){};
     }
     View itemView=inflater.inflate(R.layout.recycler_item,null);
     return new MyViewHolder(itemView);
     }
     //    View    
     @Override
     public void onBindViewHolder(RecyclerView.ViewHolder holder, int position){
     if(getItemViewType(position)==TYPE_HEADER||getItemViewType(position)==TYPE_FOOTER){
      return;
     }
     MyViewHolder myholder= (MyViewHolder) holder;
     myholder.textview.setText(datas.get(getRealPosition(position)));
     }
     //      position     1        -1
     public int getRealPosition(int position){
     return header==null?position:position-1;
     }
     //      
     @Override
     public int getItemCount() {
     if(header == null && footer == null){//  head foot
      return datas.size();
     }else if(header == null && footer != null){//head  &&foot   
      return datas.size() + 1;
     }else if (header != null && footer == null){//head   &&foot  
      return datas.size() + 1;
     }else {
      return datas.size() + 2;//head   &&foot   
     }
     }
     @Override
     public int getItemViewType(int position){
     //        &&         head  
     if(header!=null&&position==0){
      return TYPE_HEADER;
     }else if(footer!=null&&position==getItemCount()-1){//  footer   &&    
      return TYPE_FOOTER;
     }
     return super.getItemViewType(position);
     }
     public void setHeader(View header) {
     this.header = header;
    
     notifyItemInserted(0);//   0      ,    
     }
     public void setFooter(View footer) {
     this.footer = footer;
     notifyItemInserted(datas.size()-1);//         ,    
     }
     class MyViewHolder extends RecyclerView.ViewHolder{
     private TextView textview;
    
     public MyViewHolder(View itemView) {
      super(itemView);
      textview= (TextView) itemView.findViewById(R.id.textview);
     }
     }
    }
    
    getItemCount
    header 와 footer 가 있 을 때 원본 데이터 길 이 를 바탕 으로 증가 해 야 합 니 다.
    getItemViewType
    getItemView Type 을 통 해 다른 유형 을 판단 합 니 다.
    onCreateViewHolder
    다른 형식 으로 아 이 템 을 만 드 는 View
    onBindViewHolder
    만약 에 header 와 footer 형식 이 데 이 터 를 연결 할 필요 가 없다 면 header 와 footer 의 View 는 보통 activity 에서 만 들 고 이쪽 에서 처리 할 필요 가 없 기 때문에 이 두 가지 유형 을 우 리 는 아래로 실행 하지 않 습 니 다.만약 에 머리 레이아웃 이 있 으 면 position==0 의 위 치 는 header 에 의 해 점용 되 지만 우리 의 데이터 소스 즉 집합 하 표 는 0 에서 시작 되 기 때문에 여기 서-1 이 필요 합 니 다.
    setHeader
    헤드 레이아웃 을 설정 하고 첫 줄 에 데 이 터 를 삽입 한 다음 새로 고침 합 니 다.이 방법 이 호출 되면 삽 입 된 애니메이션 이 있 습 니 다.이 애니메이션 은 기본 값 을 사용 할 수도 있 고 스스로 정의 할 수도 있 습 니 다.
    setFooter
    꼬리 레이아웃 을 설정 하고 꼬리 에 데 이 터 를 삽입 한 다음 새로 고침 합 니 다.
    header 와 footer 를 추가 하 는 방법 이 마침내 봉인 되 었 습 니 다.activity 에 서 는 두 줄 의 코드 만 있 으 면 header 를 추가 할 수 있 습 니 다.ListView 가 addHeader 를 호출 하 는 방법 처럼 간단 하고 happy 하 게 놀 수 있 습 니 다.여기 서 주의해 야 할 것 은 우리 가 View 를 초기 화 할 때 inflate 방법 은 세 개의 인자 가 필요 하 다 는 것 이다.
    자원 idroot father View
  • attachToRoot true:부모 View false 로 돌아 가기:자원 id 로 생 성 된 View 를 되 돌려 줍 니 다
  • 
    //  header
    View header=LayoutInflater.from(this).inflate(R.layout.recycler_header,recyclerView,false);
    adapter.setHeader(header);
    //  footer
    View footer=LayoutInflater.from(this).inflate(R.layout.recycler_footer,recyclerView,false);
    adapter.setFooter(footer);
    
    recycler_header 와 recyclerfooter 레이아웃 파일 을 붙 이지 않 겠 습 니 다.TextView 만 있 습 니 다.우 리 는 효과 도 를 직접 봅 니 다.

    아 이 템 클릭 이벤트&&애니메이션 효과 증가 또는 삭제
    우리 가 RecyclerView 의 setOnItemClickListener 방법 을 호출 했 을 때 없 었 다 는 것 을 알 게 되 었 습 니 다.RecyclerView 를 사용 하면 모든 것 을 스스로 포장 하 는 것 에 익숙해 져 야 합 니 다.
    우선 adapter 에서 시작 하여 내부 에 인터페이스,인 스 턴 스 변 수 를 쓰 고 공공 방법 을 제공 하 며 감청 을 설정 합 니 다.
    
    private RecyclerViewItemClick recyclerViewItemClick;
    public void setRecyclerViewItemClick(RecyclerViewItemClick recyclerViewItemClick) {
     this.recyclerViewItemClick = recyclerViewItemClick;
    }
    public interface RecyclerViewItemClick{
     /**
     * item  
     * @param realPosition    position
     * @param position view position
     */
     void onItemClick(int realPosition,int position);
    }
    
    onBindView Holder 방법 에서 아 이 템 에 게 클릭 이 벤트 를 감청 합 니 다.
    
    if(recyclerViewItemClick!=null) {
     myholder.itemView.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
      recyclerViewItemClick.onItemClick(getRealPosition(position),position);
     }
     });
    }
    activity 의 onCreate 방법 에서 감청 을 하고 item 을 설정 하여 애니메이션 을 추가 삭제 합 니 다.저 는 sdk 자체 테이프 의 기본 애니메이션 을 사용 합 니 다.
    
    adapter.setRecyclerViewItemClick(recyclerViewItemClick);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    
    private RecyclerHeadFootViewAdapter.RecyclerViewItemClick recyclerViewItemClick=new RecyclerHeadFootViewAdapter.RecyclerViewItemClick() {
     @Override
     public void onItemClick(int realPosition, int position) {
     Log.i("ansen","    :"+realPosition+" view  :"+position);
     Log.i("ansen","    :"+position+"   item  :"+(adapter.getItemCount()-position-1));
     datas.remove(realPosition);//     
     adapter.notifyItemRemoved(position);//item    
     //  position adapter.getItemCount()-1   
     adapter.notifyItemRangeChanged(position,adapter.getItemCount()-position-1);
     }
    };
    
    원본 코드 다운로드
    RecyclerView
    이상 은 본 고의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 도움 이 되 기 를 바 랍 니 다.또한 저 희 를 많이 지지 해 주시 기 바 랍 니 다!

    좋은 웹페이지 즐겨찾기