Search code examples
androidarraysgridviewitems

How to set width and height of cell item in GridView programmatically in Android


I am trying to set a dynamic width and height of my GridView's items, this is my code:

 class GridAdapter extends BaseAdapter {
            private Context context;
            private GridAdapter(Context context, List<ParseObject> objects) {
                super();
                this.context = context;
            }

            // CONFIGURE CELL
            @Override
            public View getView(int position, View cell, ViewGroup parent) {
                if (cell == null) {
                    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    cell = inflater.inflate(R.layout.cell_post_search, null);
                }

                //-----------------------------------------------
                // MARK - INITIALIZE VIEWS
                //-----------------------------------------------
                ImageView postImg = cell.findViewById(R.id.cpsPostImg);
                ImageView videoicon = cell.findViewById(R.id.cpsVideoIcon);

            ...

            return cell;
            }
                @Override public int getCount() { return postsArray.size(); }
                @Override public Object getItem(int position) { return postsArray.get(position); }
                @Override public long getItemId(int position) { return position; }
        }

        // Set Adapter
        postsGridView.setAdapter(new GridAdapter(ctx, postsArray));

        // Set number of Columns accordingly to the device used
        float scalefactor = getResources().getDisplayMetrics().density * screenW/3; // LET'S PRETEND MY screenW = 720, this value whoudl, be 240, which is the width i need for my cell

        int number = getWindowManager().getDefaultDisplay().getWidth();
        int columns = (int) ((float) number / scalefactor);
        postsGridView.setNumColumns(columns);
        Log.i(Configurations.TAG, "SCALE FACTOR: " + scalefactor);

And here's my custom cell_post_search.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/cpsCellLayout"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true">

        <ImageView
            android:id="@+id/cpsPostImg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:background="#c1c1c1"
            android:scaleType="centerCrop"/>

        <ImageView
            android:id="@+id/cpsVideoIcon"
            android:layout_width="44dp"
            android:layout_height="44dp"
            android:layout_alignEnd="@+id/cpsPostImg"
            android:layout_alignParentTop="true"
            android:layout_marginRight="5dp"
            android:layout_marginTop="5dp"
            android:visibility="invisible"
            app:srcCompat="@drawable/play_butt"/>

        <ImageView
            android:id="@+id/cpsWhiteFrame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:srcCompat="@drawable/white_frame"/>
    </RelativeLayout>
</RelativeLayout>

I get 480.0 as scale factor in my Logcat, which is not the right size I need (in my case it should be 240). Anyway, I've also tried to do this:

int columns = (int) ((float) number / (scalefactor/2));

So the scalefactor = 240, but it doesn't matter, because I need my cell's item to be square size, so basically: WIDTH = screenWidth/3, HEIGHT = screenWidth/3.

It doesn't work properly, my GridView shows 3 columns but cells get stretched in width - height looks fine - as shown here:

Stretched width for cells

Is there a way to edit my code and make cells size correctly, as square images, 3 columns, based on the device size?


Solution

  • Try This

     class GridAdapter extends BaseAdapter {
            private Context context;
            private GridAdapter(Context context, List<ParseObject> objects) {
                super();
                this.context = context;
            }
    
            // CONFIGURE CELL
            @Override
            public View getView(int position, View cell, ViewGroup parent) {
                if (cell == null) {
                    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    cell = inflater.inflate(R.layout.cell_post_search, null);
                }
    
                //-----------------------------------------------
                // MARK - INITIALIZE VIEWS
                //-----------------------------------------------
                ImageView postImg = cell.findViewById(R.id.cpsPostImg);
                ImageView videoicon = cell.findViewById(R.id.cpsVideoIcon);
    
                DisplayMetrics displayMetrics = new DisplayMetrics();
                ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                int width = displayMetrics.widthPixels;
                postImg.getLayoutParams().height = width / 3;
    
            ...
    
            return cell;
            }
                @Override public int getCount() { return postsArray.size(); }
                @Override public Object getItem(int position) { return postsArray.get(position); }
                @Override public long getItemId(int position) { return position; }
        }
    


    Also, in your XML layout, add android:numColumns="3":

    <GridView
                android:id="@+id/upPostsGridView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:numColumns="3"/>