1. 程式人生 > >RecyclerView系列(五)item顯示列數切換

RecyclerView系列(五)item顯示列數切換

效果圖

效果圖

實現原理

RecyclerView搭配GridLayoutManager manager = new GridLayoutManager(this, 3)構造出三列顯示的Manager,在更改每行顯示列數的開關使用manager.setSpanSizeLookup()動態更改每個item佔用的列數。

程式碼實現

因為該功能實現原理較為簡單,所以直接給出程式碼,有興趣的童鞋請cory程式碼進行實現。

該篇文章效果在app內路徑為:
3D選單-左下角Home圖示-RecyclerView總介面-RecyclerView單雙列切換

Activity樣式佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="com.example.zpf.animmenu.RecyclerViewSwitchActivity">
<android.support.v7.widget.SwitchCompat android:id="@+id/switch_count" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd
="16dp" android:layout_marginTop="16dp" android:textOff="off" android:textOn="on" android:text="RecyclerView顯示三列資料" android:textColor="@color/colorGrayDarkDark" android:textSize="12sp" app:switchPadding="16dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintEnd_toEndOf="parent" />
<android.support.constraint.Guideline android:id="@+id/guild_line" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintGuide_percent="0.1" /> <android.support.v7.widget.RecyclerView android:id="@+id/rv_count_switch" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/guild_line" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> </android.support.constraint.ConstraintLayout>

Adapter所用的item佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardCornerRadius="0dp"
    app:cardElevation="4dp"
    app:contentPadding="4dp"
    app:cardUseCompatPadding="true">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <ImageView
            android:id="@+id/iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@mipmap/wall"
            android:contentDescription="@null"/>

        <TextView
            android:id="@+id/tv"
            android:layout_gravity="bottom"
            android:layout_width="match_parent"
            android:layout_height="64dp"
            android:background="@color/black_alpha_6"
            android:padding="8dp"
            android:maxLines="2"
            android:textColor="@color/colorWhite"
            android:lineSpacingMultiplier="1.2"
            android:ellipsize="end"/>

    </FrameLayout>

</android.support.v7.widget.CardView>

RecyclerView所用Adapter程式碼

package adapter;

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.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.zpf.animmenu.R;

import java.util.ArrayList;
import java.util.List;


/**
 * 單雙列切換的adapter
 */
public class RecyclerViewSwitchAdapter extends RecyclerView.Adapter<RecyclerViewSwitchAdapter.GridViewHolder> {

    private Context mContext;
    private ArrayList<String> urls = new ArrayList<>();
    private LayoutInflater inflater;

    public RecyclerViewSwitchAdapter(Context contexts, List<String> strings) {

        this.mContext = contexts;
        inflater = LayoutInflater.from(contexts);
        this.urls.addAll(strings);
    }

    @Override
    public GridViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.item_count_switch, parent, false);
        return new GridViewHolder(view);
    }

    @Override
    public void onBindViewHolder(GridViewHolder holder, int position) {

        Glide.with(mContext).load(urls.get(position))
                .asBitmap().placeholder(R.mipmap.bg_loading)
                .error(R.mipmap.ic_launcher)
                .into(holder.iv);

        holder.tv.setText(urls.get(position));
    }

    @Override
    public int getItemCount() {
        return urls.size();
    }

    class GridViewHolder extends RecyclerView.ViewHolder {

        private ImageView iv;
        private TextView tv;

        private GridViewHolder(View itemView) {
            super(itemView);
            iv = (ImageView) itemView.findViewById(R.id.iv);
            tv = (TextView) itemView.findViewById(R.id.tv);
        }

    }

}

Activity java程式碼

package com.example.zpf.animmenu;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.widget.CompoundButton;

import java.util.ArrayList;
import java.util.Arrays;

import adapter.RecyclerViewSwitchAdapter;

public class RecyclerViewSwitchActivity extends AppCompatActivity implements
        CompoundButton.OnCheckedChangeListener {

    private GridLayoutManager manager;
    private RecyclerViewSwitchAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view_switch);

        initView();
    }

    private void initView() {

        SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch_count);
        switchCompat.setOnCheckedChangeListener(this);

        initRecyclerView();
    }

    private void initRecyclerView() {

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.rv_count_switch);

        manager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(manager);
        recyclerView.setHasFixedSize(true);

        ArrayList<String> urls = new ArrayList<>();
        urls.addAll(Arrays.asList(getResources().getStringArray(R.array.picUrls)));
        adapter = new RecyclerViewSwitchAdapter(this, urls);

        recyclerView.setAdapter(adapter);

        changeShowItemCount(1);
    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

        int count = b ? 3 : 1;
        changeShowItemCount(count);
    }

    /**
     * 更改每行顯示數目
     */
    private void changeShowItemCount(int count) {

        final int i = 4 - count;
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                return i;
            }
        });
        adapter.notifyDataSetChanged();
    }
}

That’s all! Thankyou!