Thursday, March 16, 2017

android - RecyclerView in different screen size and orientation example

activity_main.xml

<?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:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#c7c9bf"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.RelativeLayout;


public class MainActivity extends AppCompatActivity{
    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRootLayout;
    private RecyclerView mRecyclerView;

    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

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

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        getSupportActionBar().setTitle(
                getScreenSizeCategory()
                + " - " + getScreenOrientation());

        // Get the widget reference from XML layout
        mRootLayout = (RelativeLayout) findViewById(R.id.root_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        // Specify the recycler view layout
        mLayoutManager = new GridLayoutManager(mContext,calculateNumberOfColumns(2));
        mRecyclerView.setLayoutManager(mLayoutManager);

        // Initialize a new string array of flowers
        String[] flowers = new String[]{
                "African lily",
                "Alpine thistle",
                "Amaryllis",
                "Amazon lily",
                "Arum Lily",
                "Busy Lizzie",
                "Calla lily",
                "Carnation",
                "Chincerinchee",
                "Cockscomb",
                "Columbine",
                "Coneflower",
                "Cornflower",
                "Daffodil",
                "Foxglove"
        };

        // Data bind the recycler view with adapter
        mAdapter = new FlowerRecyclerViewAdapter(flowers);
        mRecyclerView.setAdapter(mAdapter);
    }

    // Custom method to calculate number of columns for grid type recycler view
    protected int calculateNumberOfColumns(int base){
        int columns = base;
        String screenSize = getScreenSizeCategory();

        if(screenSize.equals("small")){
            if(base!=1){
                columns = columns-1;
            }
        }else if (screenSize.equals("normal")){
            // Do nothing
        }else if(screenSize.equals("large")){
            columns += 2;
        }else if (screenSize.equals("xlarge")){
            columns += 3;
        }

        if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
            columns = (int) (columns * 1.5);
        }

        return columns;
    }

    // Custom method to get screen current orientation
    protected String getScreenOrientation(){
        String orientation = "undefined";

        if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){
            orientation = "landscape";
        }else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
            orientation = "portrait";
        }

        return orientation;
    }

    // Custom method to get screen size category
    protected String getScreenSizeCategory(){
        int screenLayout = getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK;

        switch(screenLayout){
            case Configuration.SCREENLAYOUT_SIZE_SMALL:
                // small screens are at least 426dp x 320dp
                return "small";
            case Configuration.SCREENLAYOUT_SIZE_NORMAL:
                // normal screens are at least 470dp x 320dp
                return "normal";
            case Configuration.SCREENLAYOUT_SIZE_LARGE:
                // large screens are at least 640dp x 480dp
                return "large";
            case Configuration.SCREENLAYOUT_SIZE_XLARGE:
                // xlarge screens are at least 960dp x 720dp
                return "xlarge";
            default:
                return "undefined";
        }
    }
}
res/layout/custom_view_flower_holder.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:id="@+id/linear_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="25dp"
        />
</LinearLayout>
FlowerRecyclerViewAdapter.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Random;


public class FlowerRecyclerViewAdapter extends RecyclerView.Adapter<FlowerRecyclerViewAdapter.ViewHolder> {
    private String[] mDataArray;

    public FlowerRecyclerViewAdapter(String[] array){
        mDataArray = array;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        private LinearLayout root_layout;
        public TextView title;
        public ViewHolder(View v){
            super(v);
            title = (TextView) v.findViewById(R.id.text_view);
            root_layout = (LinearLayout) v.findViewById(R.id.linear_layout);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position){
        holder.title.setText(mDataArray[position]);
        holder.root_layout.setBackgroundColor(getRandomHSVColor());
    }

    @Override
    public int getItemCount(){
        return mDataArray.length;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_view_flower_holder,parent,false);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    // Custom method to generate random HSV color
    protected int getRandomHSVColor(){
        // Generate a random hue value between 0 to 360
        int hue = new Random().nextInt(361);
        // We make the color depth full
        float saturation = 1.0f;
        // We make a full bright color
        float value = 1.0f;
        // We avoid color transparency
        int alpha = 255;
        // Finally, generate the color
        int color = Color.HSVToColor(alpha, new float[]{hue, saturation, value});
        // Return the color
        return color;
    }
}