TheJadav

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(R.id.gridView);

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);

gridView.setNumColumns(numColumns);




For Recyclerview use this layout manager :

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;

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) {
        updateSpanCount();
        super.onLayoutChildren(recycler, state);
    }

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

Share this content:

Share:

More Posts

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message