Thursday, December 17, 2015

Android RecyclerView 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/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#ffffff"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:background="#62895b"
        android:padding="10dp"
        >
    </android.support.v7.widget.RecyclerView>
</RelativeLayout>
custom_view.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:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        android:textColor="#ffffff"
        android:textSize="20dp"
        android:textStyle="bold"
        android:layout_margin="2dp"
        android:padding="5dp"
        />
</LinearLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Window;
import android.widget.RelativeLayout;


public class MainActivity extends AppCompatActivity {
    private Context mContext;

    RelativeLayout mRelativeLayout;
    private RecyclerView mRecyclerView;

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


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();

        // Change the action bar color
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLUE));

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        // Initialize a new String array
        String[] colors = {
                "Red","Green","Blue","Yellow","Magenta","Cyan","Orange",
                "Aqua","Azure","Beige","Bisque","Brown","Coral","Crimson"
        };

        // Define a layout for RecyclerView
        mLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(mLayoutManager);

        // Initialize a new instance of RecyclerView Adapter instance
        mAdapter = new ColorAdapter(mContext,colors);

        // Set the adapter for RecyclerView
        mRecyclerView.setAdapter(mAdapter);
   }
}
ColorAdapter.java

package com.cfsuman.me.androidcode;

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;


public class ColorAdapter extends RecyclerView.Adapter<ColorAdapter.ViewHolder>{
    private String[] mDataSet;
    private Context mContext;

    public ColorAdapter(Context context,String[] DataSet){
        mDataSet = DataSet;
        mContext = context;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        public TextView mTextView;
        public ViewHolder(View v){
            super(v);
            mTextView = (TextView)v.findViewById(R.id.tv);
        }
    }

    /*
        public abstract VH onCreateViewHolder (ViewGroup parent, int viewType)
            Called when RecyclerView needs a new RecyclerView.ViewHolder of the given
            type to represent an item.

            This new ViewHolder should be constructed with a new View that can represent the items
            of the given type. You can either create a new View manually or inflate it from
            an XML layout file.

            The new ViewHolder will be used to display items of the adapter using
            onBindViewHolder(ViewHolder, int, List). Since it will be re-used to display
            different items in the data set, it is a good idea to cache references to sub views
            of the View to avoid unnecessary findViewById(int) calls.

        Parameters
            parent : The ViewGroup into which the new View will be added after it is bound to an adapter position.
            viewType : The view type of the new View.
        Returns
            A new ViewHolder that holds a View of the given view type.
    */
    @Override
    public ColorAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        // Create a new View
        View v = LayoutInflater.from(mContext).inflate(R.layout.custom_view,parent,false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    /*
        public abstract void onBindViewHolder (VH holder, int position)
            Called by RecyclerView to display the data at the specified position. This method should
            update the contents of the itemView to reflect the item at the given position.

            Note that unlike ListView, RecyclerView will not call this method again if the position
            of the item changes in the data set unless the item itself is invalidated or the new
            position cannot be determined. For this reason, you should only use the position
            parameter while acquiring the related data item inside this method and should not keep
            a copy of it. If you need the position of an item later on (e.g. in a click listener),
            use getAdapterPosition() which will have the updated adapter position. Override
            onBindViewHolder(ViewHolder, int, List) instead if Adapter can handle efficient partial bind.

        Parameters
            holder : The ViewHolder which should be updated to represent the contents of the item
                at the given position in the data set.
            position : The position of the item within the adapter's data set.
    */
    @Override
    public void onBindViewHolder(ViewHolder holder, int position){
        holder.mTextView.setText(mDataSet[position]);
    }

    /*
        public abstract int getItemCount ()
            Returns the total number of items in the data set hold by the adapter.

        Returns
            The total number of items in this adapter.
    */
    @Override
    public int getItemCount(){
        return mDataSet.length;
    }
}
build.gradle [dependencies]

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