欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android RecyclerView加载不同布局简单实现

程序员文章站 2024-03-07 20:01:45
前言 关于recyclerview的使用这里就不在赘述了,相信网上一搜一大把(本人之前的文章也有简单的使用介绍),这次我们讲的是recyclerview在使用的过程中,有...

前言

关于recyclerview的使用这里就不在赘述了,相信网上一搜一大把(本人之前的文章也有简单的使用介绍),这次我们讲的是recyclerview在使用的过程中,有时候会根据不同的位置加载不同的布局的简单实现,这里只是起到抛砖引玉的作用

效果图

Android RecyclerView加载不同布局简单实现

设计思想
 •重写recyclerview.adapter的getitemviewtype(int position),
在此方法中根据不同的position,设置不同的viewtype
 •编写具体的recyclerview.viewholder子类(不同子类对应不同view或layout)
 •重写recyclerview.adapter的oncreateviewholder(viewgroup parent,int viewtype)
在此方法中根据我们之前设置的viewtype来返回不同的recyclerview.viewholder的子类 

代码

使用recyclerview需要添加依赖

compile 'com.android.support:recyclerview-v7:24.1.1'

首先是mainactivity布局,很简单的布局

<?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="com.example.hfs.recyclerviewloadlayout.mainactivity">

  <android.support.v7.widget.recyclerview
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</relativelayout>

然后是mainactivity代码

package com.example.hfs.recyclerviewloadlayout;

import android.support.v7.app.appcompatactivity;
import android.os.bundle;
import android.support.v7.widget.linearlayoutmanager;
import android.support.v7.widget.recyclerview;
import android.view.view;
import android.widget.toast;

import java.util.arraylist;
import java.util.list;

public class mainactivity extends appcompatactivity {

  private recyclerview mrecyclerview;

  @override
  protected void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.activity_main);

    initview();

    initdata();
  }

  private void initdata() {
    list<string> descs = new arraylist<>();
    descs.clear();

    list<integer> images = new arraylist<>();
    images.clear();

    for (int i = 1; i < 21; i++) {
      descs.add("测试数据" + (i < 10 ? "0" + i : i));
    }

    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);
    images.add(r.mipmap.ic_launcher);

    myadapter adapter = new myadapter(mainactivity.this, descs, images);
    mrecyclerview.setadapter(adapter);
    recyclerview.layoutmanager manager = new linearlayoutmanager(mainactivity.this, linearlayoutmanager.vertical, false);
    mrecyclerview.setlayoutmanager(manager);
    mrecyclerview.additemdecoration(new divideritemdecoration(mainactivity.this, divideritemdecoration.vertical_list));

    adapter.setmonitemclicklistener(new myadapter.onitemclicklistener() {
      @override
      public void onitemclick(view view, int position) {
        toast.maketext(mainactivity.this, "点击了" + position + "位置", toast.length_short).show();
      }
    });
  }

  private void initview() {
    mrecyclerview= (recyclerview) findviewbyid(r.id.recyclerview);
  }
}

然后是我们的适配器

package com.example.hfs.recyclerviewloadlayout;

import android.content.context;
import android.support.v7.widget.recyclerview;
import android.view.view;
import android.view.viewgroup;
import android.widget.imageview;
import android.widget.textview;

import java.util.arraylist;
import java.util.list;

/**
 * created by hfs on 2016/8/24.
 */
public class myadapter extends recyclerview.adapter<recyclerview.viewholder> {

  private context mcontext;
  private list<string> descs;
  private list<integer> images;
  private list<object> alllist;

  private static final int textview_viewtype = 1;
  private static final int imageview_viewtype = 2;

  public interface onitemclicklistener {
    void onitemclick(view view, int position);
  }

  private onitemclicklistener monitemclicklistener;

  public onitemclicklistener getmonitemclicklistener() {
    return monitemclicklistener;
  }

  public void setmonitemclicklistener(onitemclicklistener monitemclicklistener) {
    this.monitemclicklistener = monitemclicklistener;
  }

  public myadapter(context mcontext, list<string> descs, list<integer> images) {
    this.mcontext = mcontext;
    this.descs = descs;
    this.images = images;

    alllist = new arraylist<>();
    alllist.clear();
    for (int i = 0; i < descs.size(); i++) {
      alllist.add(descs.get(i));
      alllist.add(images.get(i));
    }
  }

  @override
  public recyclerview.viewholder oncreateviewholder(viewgroup parent, int viewtype) {
    recyclerview.viewholder holder = getviewholderbyviewtype(viewtype);
    return holder;
  }

  private recyclerview.viewholder getviewholderbyviewtype(int viewtype) {

    view tv_itemview = view.inflate(mcontext, r.layout.item_tv, null);
    view iv_itemview = view.inflate(mcontext, r.layout.item_iv, null);

    recyclerview.viewholder holder = null;
    switch (viewtype) {
      case textview_viewtype:
        holder = new mytextview_viewholder(tv_itemview);
        break;
      case imageview_viewtype:
        holder = new myimageview_viewholder(iv_itemview);
        break;
    }
    return holder;
  }

  @override
  public int getitemviewtype(int position) {
    int viewtype = -1;
    int index = position % 2;
    switch (index) {
      case 0:
        viewtype = textview_viewtype;
        break;
      case 1:
        viewtype = imageview_viewtype;
        break;
    }
    return viewtype;
  }

  @override
  public void onbindviewholder(recyclerview.viewholder holder, final int position) {
    if (position % 2 == 0) {
      ((mytextview_viewholder) holder).tv.settext(((string) alllist.get(position)));
      ((mytextview_viewholder) holder).view.setonclicklistener(new view.onclicklistener() {
        @override
        public void onclick(view v) {
          if (monitemclicklistener != null) {
            monitemclicklistener.onitemclick(v, position);
          }
        }
      });

    } else {
      ((myimageview_viewholder) holder).iv.setimageresource(((integer) alllist.get(position)));
      ((myimageview_viewholder) holder).view.setonclicklistener(new view.onclicklistener() {
        @override
        public void onclick(view v) {
          if (monitemclicklistener != null) {
            monitemclicklistener.onitemclick(v, position);
          }
        }
      });
    }
  }

  @override
  public int getitemcount() {
    return alllist.size();
  }

  class mytextview_viewholder extends recyclerview.viewholder {
    public view view;
    public textview tv;

    public mytextview_viewholder(view itemview) {
      super(itemview);
      this.view = itemview;
      this.tv = (textview) itemview.findviewbyid(r.id.tv);
    }
  }

  class myimageview_viewholder extends recyclerview.viewholder {

    public view view;
    public imageview iv;

    public myimageview_viewholder(view itemview) {
      super(itemview);
      this.view = itemview;
      this.iv = (imageview) itemview.findviewbyid(r.id.iv);
    }
  }
}

接着就是我们自定义的divideritemdecoration

package com.example.hfs.recyclerviewloadlayout;

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 hfs on 2016/8/24.
 */
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);
    }
  }
}

项目地址:https://github.com/greathfs/recyclerviewloadlayout

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。