Tuesday, June 2, 2020

Android Example: RecyclerView StaggeredGridLayoutManager Example

Android Example: RecyclerView StaggeredGridLayoutManager Example

1.1 What is RecyclerView?
The RecyclerView widget is a more advanced and flexible version of ListView.
1.2 Why RecyclerView?
RecyclerView is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.
1.3 When you should use RecyclerView?
You can use the RecyclerView widget when you have data collections whose elements changes at runtime based on user action or network events.
RecyclerView StaggeredGridLayoutManager Example

Step 1 Create Layout Files
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.support.v7.widget.RecyclerView>
</RelativeLayout>
Step 2 Create Layout Files
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:cardMaxElevation="2dp"
    card_view:cardElevation="1dp"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:textSize="20dp"
        android:layout_margin="2dp"
        android:padding="5dp"
        android:layout_gravity="center"
        android:gravity="center"
        android:fontFamily="sans-serif-condensed"
        />
</android.support.v7.widget.CardView>
Step 3 Create class Files
MainActivity.java
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.RED));
        // 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"
        };
        /*
            StaggeredGridLayoutManager
                A LayoutManager that lays out children in a staggered grid formation. It supports
                horizontal & vertical layout as well as an ability to layout children in reverse.
                Staggered grids are likely to have gaps at the edges of the layout. To avoid these
                gaps, StaggeredGridLayoutManager can offset spans independently or move items
                between spans. You can control this behavior via setGapStrategy(int).
        */
        /*
            public StaggeredGridLayoutManager (int spanCount, int orientation)
                Creates a StaggeredGridLayoutManager with given parameters.
            Parameters
                spanCount : If orientation is vertical, spanCount is number of columns.
                    If orientation is horizontal, spanCount is number of rows.
                orientation : VERTICAL or HORIZONTAL
        */
        // Define a layout for RecyclerView
        mLayoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        // Initialize a new instance of RecyclerView Adapter instance
        mAdapter = new ColorAdapter(mContext,colors);
        // Set the adapter for RecyclerView
        mRecyclerView.setAdapter(mAdapter);
   }
}
Step 4 Create class Files
ColorAdapter.java
public class ColorAdapter extends RecyclerView.Adapter<ColorAdapter.ViewHolder>{
    private String[] mDataSet;
    private Context mContext;
    private Random mRandom = new Random();
    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);
        }
    }
    @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;
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position){
        holder.mTextView.setText(mDataSet[position]);
        // Set a random height for TextView
        holder.mTextView.getLayoutParams().height = getRandomIntInRange(250,75);
        // Set a random color for TextView background
        holder.mTextView.setBackgroundColor(getRandomHSVColor());
    }
    @Override
    public int getItemCount(){
        return mDataSet.length;
    }
    // Custom method to get a random number between a range
    protected int getRandomIntInRange(int max, int min){
        return mRandom.nextInt((max-min)+min)+min;
    }
    // Custom method to generate random HSV color
    protected 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;
    }
}
Step 5 import file build.gradle
  implementation 'com.android.support:cardview-v7:28.0.0'
  implementation 'com.android.support:recyclerview-v7:28.0.0'

No comments:

Post a Comment