Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

RecyclerView 多種 Item 佈局實作:Header + Body + Footer 一次搞懂

編輯:關於 Android 程式設計

RecyclerView 要在一個列表裡混搭多種樣式,關鍵是 getItemViewType()。只要把位置映射成型別,剩下的交給 onCreateViewHolder() 與 onBindViewHolder() 分流即可。

MainActivity:含上拉載入更多

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);
        // 系統內建的分割線
        mRecyclerView.addItemDecoration(
                new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
        // 增刪動畫
        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);
                            // 注意:footer 之後才插入,位置要減掉 footer 數量
                            mAdapter.notifyItemInserted(mAdapter.getItemCount() - 2);
                        }
                    }, 1500);
                }
                int firstCompletelyVisibleItemPosition =
                        mLayoutManager.findFirstCompletelyVisibleItemPosition();
                if (firstCompletelyVisibleItemPosition == 0 && dy < 0) {
                    // 已回到頂部,可在此做下拉刷新
                }
            }
        });
    }
}

MyAdapter:型別分流的三個步驟

對外部只暴露三個 List(頭、身、腳),各自獨立計數;內部則負責把 position 換算成各清單的索引,這段最容易出錯,需要慢慢對。

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int HEAD_TYPE = 1;
    private static final int BODY_TYPE = 2;
    private static final int FOOT_TYPE = 3;

    private Context context;
    private List<String> mHeadList;
    private List<String> mBodyList;
    private List<String> mFootList;

    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;
    }

    // ★ 步驟一:定義位置屬於哪一種 ViewType
    @Override
    public int getItemViewType(int position) {
        if (position < getHeadCount()) {
            return HEAD_TYPE;
        } else if (position > getHeadCount() + getBodyCount() - 1) {
            // 這裡最後要減 1,慢慢數就會發現
            return FOOT_TYPE;
        } else {
            return BODY_TYPE;
        }
    }

    // ★ 步驟二:依 ViewType 決定載入哪個佈局、回傳哪個 ViewHolder
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view;
        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;
    }

    // ★ 步驟三:依 holder 的實際型別決定要操作哪個佈局
    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
        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);
    }

    /** 一次新增多筆 */
    public void addData() {
        mBodyList.add("1");
        mBodyList.add("2");
        mBodyList.add("3");
        notifyItemRangeInserted(0, 3);
    }

    /** 刪除 body 項目 */
    public void removeData(int position) {
        // 連續快速點擊時 position 可能為負數,需先擋掉
        if (position - getHeadCount() >= 0) {
            // 記得扣掉 header 數量才是 body 清單的索引
            mBodyList.remove(position - getHeadCount());
            notifyItemRemoved(position);
        }
    }

    static class HeadHolder extends RecyclerView.ViewHolder {
        private TextView mTvHead;
        HeadHolder(View itemView) {
            super(itemView);
            mTvHead = (TextView) itemView.findViewById(R.id.tv_head);
        }
    }

    static class BodyHolder extends RecyclerView.ViewHolder {
        private TextView mTvBody;
        BodyHolder(View itemView) {
            super(itemView);
            mTvBody = (TextView) itemView.findViewById(R.id.tv_body);
        }
    }

    static class FootHolder extends RecyclerView.ViewHolder {
        private TextView mTvFoot;
        FootHolder(View itemView) {
            super(itemView);
            mTvFoot = (TextView) itemView.findViewById(R.id.tv_foot);
        }
    }
}

item_body 佈局

item_head 與 item_foot 結構類似,這裡只列 body:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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:layout_gravity="center"
        android:textSize="17sp"
        android:text="Hello World!"/>
</LinearLayout>

最容易出錯的地方

整個範例的風險點都在索引換算:position - getHeadCount() 決定 body 索引,position - getHeadCount() - getBodyCount() 決定 footer 索引,而上拉載入時 notifyItemInserted 的位置又必須避開 footer。建議把這幾個換算抽成 getBodyIndex(position) 之類的方法集中管理,並且在 getItemViewType 中改用「頭數量、尾數量」的區間判斷,比連續的 if 更不容易寫錯。

另外,若你的 header 是單一固定式樣(例如輪播圖),與其塞進 adapter,用 ConcatAdapter 把多個 adapter 串起來會乾淨得多,型別判斷與索引換算的問題自然消失。

以上就是本文的全部內容,希望對你的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved