Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 中RecyclerView多種item布局的寫法(頭布局+腳布局)

Android 中RecyclerView多種item布局的寫法(頭布局+腳布局)

編輯:關於Android編程

RecyclerView多個item布局的寫法(頭布局+腳布局)

上圖

圖1

圖2

github

下載源碼

Initial commit第一次提交的代碼,為本文內容

以下的為主要代碼,看注釋即可,比較簡單

MainActivity

含上拉加載更多

package com.anew.recyclerviewall;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
  private RecyclerView mRecyclerView;
  private List<String> mHeadList;
  private List<String> mBodyList;
  private List<String> mFootList;
  private MyAdapter mAdapter;
  private LinearLayoutManager mLayoutManager;
  Handler mHandler = new Handler();
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    mHeadList = new ArrayList<>();
    for (int i = 0; i < 1; i++) {
      mHeadList.add("head" + i);
    }
    mBodyList = new ArrayList<>();
    for (int i = 'A'; i < 'L'; i++) {
      mBodyList.add("" + (char) i);
    }
    mFootList = new ArrayList<>();
    for (int i = 0; i < 1; i++) {
      mFootList.add("foot" + i);
    }
    mRecyclerView = (RecyclerView) findViewById(R.id.rv);
//    使用默認的api繪制分割線
    mRecyclerView.addItemDecoration
        (new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
//    設置增加刪除item的動畫效果
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//    瀑布流
//    mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));
    mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new MyAdapter(this, mHeadList, mBodyList, mFootList);
    mRecyclerView.setAdapter(mAdapter);
    // 當目前的可見條目是所有數據的最後一個時,開始加載新的數據
    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
      @Override
      public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        int lastCompletelyVisibleItemPosition = mLayoutManager.findLastCompletelyVisibleItemPosition();
        if (lastCompletelyVisibleItemPosition + 1 == mAdapter.getItemCount()) {
          mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
              List<String> mMoreList = new ArrayList<>();
              for (int i = 0; i < 3; i++) {
                mMoreList.add("more" + i);
              }
              mBodyList.addAll(mMoreList);
              mAdapter.notifyItemInserted(mAdapter.getItemCount() - 2);
            }
          }, 1500);
          Log.e("qqq", "到底了" + lastCompletelyVisibleItemPosition);
        }
        int firstCompletelyVisibleItemPosition = mLayoutManager.findFirstCompletelyVisibleItemPosition();
        if (firstCompletelyVisibleItemPosition == 0&&dy<0) {
          Log.e("eeeee", "開始刷新呀呀呀");
        }
      }
    });
  }
}

MyAdapter

對外部:頭布局list、身體布局list、腳布局list,所有的list單獨計數

內部:對position進行調整,這裡需要耐心調整position

package com.anew.recyclerviewall;
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 android.widget.Toast;
import java.util.List;
/**
 * Created by a on 2017/1/7.
 */
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
  private Context context;
  private List<String> mHeadList;
  private List<String> mBodyList;
  private List<String> mFootList;
  private static final int HEAD_TYPE = 1;
  private static final int BODY_TYPE = 2;
  private static final int FOOT_TYPE = 3;
  public MyAdapter(Context context, List<String> headList, List<String> bodyList, List<String> footList) {
    this.context = context;
    this.mHeadList = headList;
    this.mBodyList = bodyList;
    this.mFootList = footList;
  }
  //  ★ 1. 定義規則,什麼情況,是哪一種ViewType
  @Override
  public int getItemViewType(int position) {
    int viewType = -1;
    if (position < getHeadCount()) {
      viewType = HEAD_TYPE;
    } else if (position > getHeadCount() + getBodyCount() - 1) {
      //這裡最後要減去1,慢慢地去數
      viewType = FOOT_TYPE;
    } else {
      viewType = BODY_TYPE;
    }
    return viewType;
  }
  @Override
  public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = null;
    //  ★ 2. 根據viewType來確定加載那個布局,返回哪一個ViewHolder
    switch (viewType) {
      case HEAD_TYPE:
        view = inflater.inflate(R.layout.item_head, parent, false);
        return new HeadHolder(view);
      case BODY_TYPE:
        view = inflater.inflate(R.layout.item_body, parent, false);
        return new BodyHolder(view);
      case FOOT_TYPE:
        view = inflater.inflate(R.layout.item_foot, parent, false);
        return new FootHolder(view);
    }
    return null;
  }
  @Override
  public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
// ★ 3. 根據holder是哪一個ViewHolder的實例,來確定操作哪一個布局的UI
    if (holder instanceof HeadHolder) {
      HeadHolder headHolder = (HeadHolder) holder;
      headHolder.mTvHead.setText(mHeadList.get(position) + "");
      headHolder.mTvHead.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          addData();
        }
      });
    }
    if (holder instanceof BodyHolder) {
      final BodyHolder bodyHolder = (BodyHolder) holder;
      bodyHolder.mTvBody.setText(mBodyList.get(position - getHeadCount()) + "");
      bodyHolder.mTvBody.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          removeData(bodyHolder.getAdapterPosition());
        }
      });
    }
    if (holder instanceof FootHolder) {
      final FootHolder footHolder = (FootHolder) holder;
      footHolder.mTvFoot.setText(mFootList.get(position - getHeadCount() - getBodyCount()) + "");
      footHolder.mTvFoot.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          Toast.makeText(context, footHolder.getAdapterPosition() + "",
              Toast.LENGTH_SHORT).show();
        }
      });
    }
  }
  @Override
  public int getItemCount() {
    return getHeadCount() + getBodyCount() + getFootCount();
  }
  private int getFootCount() {
    return mFootList.size();
  }
  private int getBodyCount() {
    return mBodyList.size();
  }
  private int getHeadCount() {
    return mHeadList.size();
  }
  public void addData(int position) {
    mBodyList.add(position, "Insert One");
//    ★★★★ 使用notifyItemInserted去更新數據,否則沒有動畫效果
    notifyItemInserted(position);
  }
  /**
   * 增加bodyList條目
   */
  public void addData() {
    mBodyList.add("1");
    mBodyList.add("2");
    mBodyList.add("3");
//    ★★★★ 使用notifyItemInserted去更新數據,否則沒有動畫效果
    notifyItemRangeInserted(0, 3);
  }
  /**
   * 刪除bodyList條目
   */
  public void removeData(int position) {
//    經測試瘋狂點擊刪除條目,會產生負數,導致越界異常
    if (!(position - getHeadCount() < 0)) {
//    ★★★★ 防止角標越界異常,要減去頭布局數量,總之去數數吧
      mBodyList.remove(position - getHeadCount());
      notifyItemRemoved(position);
    }
  }
  /**
   * 頭布局Holder
   */
  static class HeadHolder extends RecyclerView.ViewHolder {
    private TextView mTvHead;
    public HeadHolder(View itemView) {
      super(itemView);
      mTvHead = (TextView) itemView.findViewById(R.id.tv_head);
    }
  }
  /**
   * 身體布局Holder
   */
  static class BodyHolder extends RecyclerView.ViewHolder {
    private TextView mTvBody;
    public BodyHolder(View itemView) {
      super(itemView);
      mTvBody = (TextView) itemView.findViewById(R.id.tv_body);
    }
  }
  /**
   * 腳布局Holder
   */
  static class FootHolder extends RecyclerView.ViewHolder {
    private TextView mTvFoot;
    public FootHolder(View itemView) {
      super(itemView);
      mTvFoot = (TextView) itemView.findViewById(R.id.tv_foot);
    }
  }
}

item_body

item_head和item_foot類似就不粘貼了

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/ll"
       android:layout_width="match_parent"
       android:layout_height="40dp"
       android:layout_marginRight="11px"
       android:layout_marginBottom="11px"
       android:background="@color/colorPrimary"
       android:orientation="vertical">
  <TextView
    android:id="@+id/tv_body"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textSize="17sp"
    android:layout_gravity="center"
    android:text="Hello World!"/>
</LinearLayout>

以上所述是小編給大家介紹的Android 中RecyclerView多種item布局的寫法(頭布局+腳布局),希望對大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會及時回復大家的!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved