文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

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

2022-06-06 07:44

关注

前言

关于RecyclerView的使用这里就不在赘述了,相信网上一搜一大把(本人之前的文章也有简单的使用介绍),这次我们讲的是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;

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;

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

您可能感兴趣的文章:Android RecyclerView点击事件Android RecyclerView的Item点击事件实现整理Android使用RecyclerView实现自定义列表、点击事件以及下拉刷新RecyclerView的使用之多种Item加载布局Android中RecyclerView布局代替GridView实现类似支付宝的界面Android RecyclerView网格布局(支持多种分割线)详解(2)Android RecyclerView布局就这么简单Android开发中RecyclerView模仿探探左右滑动布局功能Android 中RecyclerView多种item布局的写法(头布局+脚布局)Recyclerview添加头布局和尾布局、item点击事件详解


阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-移动开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯