Customize how to divide the contents of Recyclerview

Introduction

In some cases, the layout of the contents of Recyclerview is divided into two, below that is further divided into four, and no, there is no need to divide below this four divisions! In that way, I want to divide the contents of the recyclerview in various ways!

device.gif

like this!

References

About RecyclerView http://qiita.com/Yuki_Yamada/items/ec8b6c1ff0c9d74c2a53 About setSpan (how many items are divided) https://stackoverflow.com/questions/32366412/gridlayoutmanager-setspansizelookup-creating-blank-cells About Viewtype http://woshidan.hatenablog.com/entry/2015/11/02/083000

Library settings

build.gradle


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

Please add.

Implementation

This time, the contents of xml described in the three layout files are applied to the recyclerview. Then, the layout file is described below.

layout1.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:layout_margin="1dp"
        android:text="1"
        android:background="@color/colorAccent"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="50dp" />
</LinearLayout>

layout2.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_margin="1dp"
        android:text="2"
        android:background="@color/colorPrimaryDark"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="100dp" />
</LinearLayout>

layout3.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <TextView
        android:layout_margin="1dp"
        android:text="3"
        android:background="@color/colorPrimary"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="200dp" />
</LinearLayout>

Next, let's set the Recyclerview as usual. First, prepare a Recyclerview (Recyclerview cannot have child elements)

recyclerview.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

Next, connect Recyclerview with layout1.xml, layout2.xml, and layout3.xml by adapter.

custom_recyclerview_adapter.java


package my package;

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class custom_recyclerview_adapter extends RecyclerView.Adapter<custom_recyclerview_adapter.ViewHolder>{
    private Activity mactivity;
    private int item_count;

    public custom_recyclerview_adapter(Activity mactivity,int item_count) {
        this.mactivity = mactivity;
        this.item_count = item_count;
    }

    @Override
    public custom_recyclerview_adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View view;
        final custom_recyclerview_adapter.ViewHolder viewHold;

        /******important******/
        switch(i) {//Here, branch from the viewType of the layout to the layout you want to apply.
            case 0:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout1, viewGroup, false);
                viewHold = new custom_recyclerview_adapter.ViewHolder(view,i);
                //Equipped with click listener
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = viewHold.getAdapterPosition(); //Get position
                        Log.d("test",String.valueOf(position));//Return what number you pressed
                    }
                });
                return viewHold;
            case 1:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout2, viewGroup, false);
                viewHold = new custom_recyclerview_adapter.ViewHolder(view,i);
                //Equipped with click listener
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = viewHold.getAdapterPosition(); //Get position
                        Log.d("test",String.valueOf(position));//Return what number you pressed
                    }
                });
                return viewHold;
            case 2:
                view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout3, viewGroup, false);
                viewHold = new custom_recyclerview_adapter.ViewHolder(view,i);
                //Equipped with click listener
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = viewHold.getAdapterPosition(); //Get position
                        Log.d("test",String.valueOf(position));//Return what number you pressed
                    }
                });
                return viewHold;
        }
        /*************/
        return null;
    }

    @Override//Make changes to the view here
    public void onBindViewHolder(custom_recyclerview_adapter.ViewHolder viewHolder, int i) {
        //Data display
        if(0 <= i && i <= 3) {
            //viewHolder.title1.setText(test[i] + "Mr.");
        }
        else if(4 <= i && i <= 7){// creates second view
            //viewHolder.title2.setText("hello");
        }
        else{// creates third view
            //viewHolder.title3.setText("test");
        }
    }

    @Override
    public int getItemCount() {
        return item_count;
    }

    /******important*******/
    @Override
    public int getItemViewType(int position) {//position is the position of the item in the recyclerview
        if(0 <= position && position <= 3) {//Viewtype 0th to 3rd contents of recyclerview"0"Set to
            return 0;
        }
        else if(4 <= position && position <= 7){//Viewtype the 4th to 7th contents of recyclerview"1"Set to
            return 1;
        }
        else{//Other view types"2"Set to
            return 2;
        }
    }
    /*****************/

    public class ViewHolder extends RecyclerView.ViewHolder{
        /*TextView title1;
        TextView title2;
        TextView title3;*/
        public ViewHolder(View view,int i) {
            super(view);
            /*title1 = (TextView)view.findViewById(R.id.textsample);
            title2 = (TextView)view.findViewById(R.id.textsample1);
            title3 = (TextView)view.findViewById(R.id.textsample2);*/
        }
    }
}

You can set ViewType for each position with getItemViewType. You can think of ViewType as a flag.

The actors are now complete. Let's implement it! !!

MainActivity.java


package jp.app.oomae.hisaki.recyclerview_custom_layout_sample;

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

public class MainActivity extends AppCompatActivity {

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

        RecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerview);
        recyclerView.setHasFixedSize(true);//Processing performance improves when the view size is fixed
        /*****************************************important*****************************************************/
        GridLayoutManager gridLayoutManagerVertical = new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL,false);
        gridLayoutManagerVertical.setSpanSizeLookup(new Custom_Spansize(4, 2 ,1));
        recyclerView.setLayoutManager(gridLayoutManagerVertical);
        /*************************************************************************************************/
        custom_recyclerview_adapter adapter = new custom_recyclerview_adapter(this,20);//Make 20 items
        recyclerView.setAdapter(adapter);
    }
}

However, if nothing is done, an error will occur. The Span inside the Recyclerview is not set. Describe the following file.

Custom_Spansize.java


package my package;

import android.support.v7.widget.GridLayoutManager;

public class Custom_Spansize extends GridLayoutManager.SpanSizeLookup{
    private int spanCnt1, spanCnt2 , spanCnt3;

    public Custom_Spansize(int spanCnt1, int spanCnt2,int spanCnt3) {
        super();
        this.spanCnt1 = spanCnt1;
        this.spanCnt2 = spanCnt2;
        this.spanCnt3 = spanCnt3;
    }

    @Override
    public int getSpanSize(int position) {
        int result;
        if(position >= 0 && position <= 3){
            result = spanCnt1;
        }
        else if(position >= 4 && position <= 7){
            result = spanCnt2;
        }
        else {
            result = spanCnt3;
        }
        return result;
    }
}

This completes the implementation.

application

MainActivity.java


        GridLayoutManager gridLayoutManagerVertical = new GridLayoutManager(this, 4, LinearLayoutManager.VERTICAL,false);
        gridLayoutManagerVertical.setSpanSizeLookup(new Custom_Spansize(4, 2 ,1));

Change the span interval here.

         GridLayoutManager gridLayoutManagerVertical = new GridLayoutManager(this, 4,LinearLayoutManager.VERTICAL,false);

4 here is the highest number of spans.

         gridLayoutManagerVertical.setSpanSizeLookup(new Custom_Spansize(4, 2 ,1));

Change the interval with the argument here. The idea is

--First argument: 4 ÷ 4 = 1 --Second argument: 4 ÷ 2 = 2 --Third argument: 4 ÷ 1 = 4

GridLayoutManager second argument ÷ Custom_Spansize argument = span The result of the division is Span.

This is the end. We look forward to hearing from you.

This code

https://github.com/hisakioomae/recyclerview_custom_layout_sample

Recommended Posts

Customize how to divide the contents of Recyclerview
[Rails] How to get the contents of strong parameters
[Ruby] How to retrieve the contents of a double hash
How to change the contents of the jar file without decompressing
Folding and unfolding the contents of the Recyclerview
How to determine the number of parallels
How to sort the List of SelectItem
How to get the contents of Map using for statement Memorandum
How to check for the contents of a java fixed-length string
How to find the cause of the Ruby error
I want to var_dump the contents of the intent
How to get today's day of the week
Output of how to use the slice method
How to display the result of form input
[Java] How to get the authority of the folder
[Ruby On Rails] How to search the contents of params using include?
How to delete / update the list field of OneToMany
How far is the correct answer to divide the process?
How to write Scala from the perspective of Java
[Ruby] How to find the sum of each digit
How to install the root certificate of Centos7 (Cybertrust)
[Java] How to get the maximum value of HashMap
[Rails] How to change the column name of the table
[SwiftUI] How to specify the abbreviated position of Text
[Android] How to get the setting language of the terminal
How to judge the click of any area of the image
Java: Use Stream to sort the contents of the collection
How to download the old version of Apache Tomcat
[Swift] How to get the document ID of Firebase
I want to be aware of the contents of variables!
[Docker] How to see the contents of Volumes. Start a container with root privileges.
How to display the select field of time_select every 30 minutes
How to get the longest information from Twitter as of 12/12/2016
How to change the setting value of Springboot Hikari CP
How to add elements without specifying the length of the array
Let's summarize how to extend the expiration date of Rails
How to solve the problems of Java's three Blocking Queues
[Rails] How to display the list of posts by category
How to mock some methods of the class under test
How to derive the last day of the month in Java
Learn how to customize the Navigation Bar from the sample app
How to check the extension and size of uploaded files
[jsoup] How to get the full amount of a document
How to check the database of apps deployed on Heroku
How to use the form_with method
[Rails] Check the contents of the object
Replace the contents of the Jar file
How to find the average angle
How to use the wrapper class
How to use setDefaultCloseOperation () of JFrame
How to add the delete function
[Ruby] Display the contents of variables
[Swift] How to dynamically change the height of the toolbar on the keyboard
[Rails] How to get the URL of the transition source and redirect
[Swift5] How to get an array and the complement of arrays
How to set the IP address and host name of CentOS8
How to display 0 on the left side of the standard input value
[Rails / Heroku / MySQL] How to reset the DB of Rails application on Heroku
[Swift UI] How to get the startup status of the application [iOS]
[Rails] How to omit the display of the character string of the link_to method
[Rails] How to change the page title of the browser for each page