Wednesday, July 13, 2016

android - Swipe to refresh RecyclerView example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/swipe_refresh_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#9fa99c"
    >
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</android.support.v4.widget.SwipeRefreshLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
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.ArrayAdapter;

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


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

    private SwipeRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private ColorsAdapter mColorsAdapter;

    private Random mRandom = new Random();
    private List<String> mColors;
    private ArrayAdapter<String> mAdapter;


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

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

        // Get the widget reference from XML layout
        mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        // Initializing a new ArrayList
        mColors = new ArrayList<>();

        for(int i=0;i<5;i++){
            int color = getRandomHSVColor();
            mColors.add(String.valueOf(color));
        }

        // Initialize Layout Manager
        mLayoutManager = new GridLayoutManager(mContext,2);

        // Define the layout for RecyclerView
        mRecyclerView.setLayoutManager(mLayoutManager);

        // Initialize a new instance of adapter
        mColorsAdapter = new ColorsAdapter(mContext, mColors);

        // Data bind RecyclerView with adapter
        mRecyclerView.setAdapter(mColorsAdapter);

        // Set a Refresh Listener for the SwipeRefreshLayout
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // Refresh the data
                // Calls setRefreshing(false) when it is finish
                updateOperation();
            }
        });
    }

    protected void updateOperation(){
        // Add a new color to the list top
        mColors.add(0,String.valueOf(getRandomHSVColor()));

        // Notify the ArrayAdapter about recent changed
        mColorsAdapter.notifyDataSetChanged();

        // Stop progress indicator when update finish
        mSwipeRefreshLayout.setRefreshing(false);
    }

    // Custom method to generate random HSV color
    public int getRandomHSVColor(){
        // Generate a random hue value between 0 to 360
        int hue = mRandom.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;
    }
}
res/layout/custom_view.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="4dp"
    card_view:cardMaxElevation="6dp"
    card_view:contentPadding="15dp"
    android:layout_margin="5dp"
    card_view:cardBackgroundColor="#d9d899"
    >
    <TextView
        android:id="@+id/tv_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:fontFamily="sans-serif-condensed"
        android:layout_gravity="center"
        android:padding="20dp"
        />
</android.support.v7.widget.CardView>
ColorsAdapter.java

package com.cfsuman.me.androidcodesnippets;

import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.List;


public class ColorsAdapter extends RecyclerView.Adapter<ColorsAdapter.ViewHolder> {
    private Context mContext;
    private List<String> mDataSet;

    public ColorsAdapter(Context context, List<String> list){
        mContext = context;
        mDataSet = list;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        public CardView mCardView;
        public TextView mTextViewLabel;

        public ViewHolder(View v){
            super(v);
            // Get the widget reference from the custom layout
            mCardView = (CardView) v.findViewById(R.id.card_view);
            mTextViewLabel = (TextView) v.findViewById(R.id.tv_label);
        }
    }

    @Override
    public ColorsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View v = LayoutInflater.from(mContext).inflate(R.layout.custom_view,parent,false);

        // Get the TextView reference from RecyclerView current item
        final TextView tv_label = (TextView) v.findViewById(R.id.tv_label);

        // Set a click listener for the current item of RecyclerView
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get the RecyclerView current item text
                final String label = tv_label.getText().toString();

                // Display the RecyclerView clicked item label
                Toast.makeText(
                        mContext,
                        "Clicked : " + label,
                        Toast.LENGTH_SHORT
                ).show();
            }
        });

        ViewHolder vh = new ViewHolder(v);

        // Return the ViewHolder
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position){
        // Get the current item from the data set
        String color = mDataSet.get(position);

        // Set the TextView widgets text
        holder.mTextViewLabel.setText(color);

        // Set the CardView background color
        holder.mCardView.setCardBackgroundColor(Integer.parseInt(color));
    }

    @Override
    public int getItemCount(){
        // Count the items
        return mDataSet.size();
    }
}