Android: Dynamic column number in GridView and Gridlayout manager

If you want to change grid item dynamically then follow these steps. This will help you to achieve your goal.

For GridView just do :

final GridView gridView = (GridView) rootView.findViewById(;

int gridViewEntrySize = getResources().getDimensionPixelSize(R.dimen.grip_view_entry_size);
int gridViewSpacing = getResources().getDimensionPixelSize(R.dimen.grip_view_spacing);

WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

int numColumns = (display.getWidth() - gridViewSpacing) / (gridViewEntrySize + gridViewSpacing);


For Recyclerview use this layout manager :

import android.content.Context;

public class VarColumnGridLayoutManager extends GridLayoutManager {

    private int minItemWidth;

    public VarColumnGridLayoutManager(Context context, int minItemWidth) {
        super(context, 1);
        this.minItemWidth = minItemWidth;

    @Override    public void onLayoutChildren(RecyclerView.Recycler recycler,
                                 RecyclerView.State state) {
        super.onLayoutChildren(recycler, state);

    private void updateSpanCount() {
        int spanCount = getWidth() / minItemWidth;
        if (spanCount < 1) {
            spanCount = 1;

Share this content:


More Posts

Introduction to Kotlin: A Versatile and Modern Programming Language

Kotlin, a versatile and modern programming language, offers developers a concise, safe, and interoperable coding experience. With features like null safety, extension functions, and coroutines, Kotlin enhances productivity and readability, making it an attractive choice for Android development and beyond. Whether you’re new to programming or an experienced developer, exploring Kotlin opens up a world of possibilities for building robust and expressive applications.

Mastering the Android Activity Lifecycle: A Comprehensive Guide

The Android Activity Lifecycle is a fundamental concept for Android developers. It defines how an Activity behaves during its lifecycle, from creation to destruction. Understanding the Activity Lifecycle is crucial for managing resources efficiently and delivering a smooth user experience. In this blog post, we’ll briefly introduce the different states an Activity can be in and the main callback methods associated with each state. Let’s dive in and explore this important aspect of Android app development!

Table of Contents

Send Us A Message