3

I am using following code to show the GirdView items.

<GridView
            android:id="@+id/gridView"
            android:gravity="center_horizontal"
            android:layout_below="@+id/searchLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:horizontalSpacing="10dp"
            android:numColumns="3"
            android:stretchMode="columnWidth"
            android:verticalSpacing="10dp" />

Each GridItem (ImageView) is of size 92dp

What i want is to show only 3 Columns or 3 images each Row and each Top, bottom ,left right all needs to be perfectly aligned and equal.

Below is the result of above code.

enter image description here

It can be seen that spaces on left and right of the grid are very less as compared with the ones in between images and also between rows are very small.

Secondly, I am using 92dp. above is the result of S3, but when i use small screen the 3rd image doesn't get fit like in 320 dp screen.

Shouldn't using "dp" automatically adjust according to screen size?

Grégoire C
  • 1,361
  • 1
  • 13
  • 32
Muhammad Umar
  • 11,391
  • 21
  • 91
  • 193

6 Answers6

1

I think this code will help you try it :-

GridView
android:id="@+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="3"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000"/>
Piyush
  • 18,895
  • 5
  • 32
  • 63
Mitul Gedeeya
  • 886
  • 1
  • 10
  • 20
0

In xml of GridView

    <GridView 
        android:id                = "@+id/gridViewSms"
        android:layout_width      = "fill_parent"
        android:layout_height     = "fill_parent"
        android:numColumns        = "3"
        android:horizontalSpacing = "10dp"
        android:verticalSpacing   = "10dp"
        android:gravity           = "center"
        android:stretchMode       ="columnWidth">

In ImageAdapter.java

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
     private Context mContext;
     private int widthOfScrren;
     public Integer[] mThumbIds;


        // Constructor
        public ImageAdapter(Context c,int ScrrenSize,Integer[] mThumbIds){
            mContext = c;
            widthOfScrren=ScrrenSize;
            this.mThumbIds = mThumbIds;
        }

        @Override
        public int getCount() {
            return mThumbIds.length;
        }

        @Override
        public Object getItem(int position) {
            return mThumbIds[position];
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(mContext);
            imageView.setImageResource(mThumbIds[position]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

            imageView.setLayoutParams(new GridView.LayoutParams(widthOfScrren / 4,widthOfScrren / 4));
            return imageView;
        }



}

In Your Activity

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class MainActivity  extends Activity{


    private Integer[] mThumbIds = {
            R.drawable.image1 ,
            R.drawable.image2,
            R.drawable.image3,
            R.drawable.image4,
            R.drawable.image5,
            R.drawable.image6,
            R.drawable.image7,
            R.drawable.image8,
            R.drawable.image9
    };


    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        //found width of Screen for Gridview
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        int densityX = display.getWidth();



        GridView grid = (GridView) findViewById(R.id.gridViewSms);
        grid.setAdapter(new ImageAdapter(getApplicationContext(), densityX, mThumbIds));

        grid.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position ,
                    long id) {


            }
        });


    }

}

I tested it. It works.

Mahdi-bagvand
  • 1,396
  • 19
  • 40
0

In the past, I have used a GridLayout instead of GridViewso that I can keep compatibility back to api v8.

for GridLayout, I wrote a nifty little function which is placed in the activity to dynamically stretch/space the items in the grid to fill the view evenly. I wrote about it here:

https://stackoverflow.com/a/15341447/2066079

I've also copied the code below for your convenience:

public void fillview(android.support.v7.widget.GridLayout gl)
{
    Button buttontemp;

    //Stretch buttons
    int idealChildWidth = (int) ((gl.getWidth()-20*gl.getColumnCount())/gl.getColumnCount());
    for( int i=0; i< gl.getChildCount();i++)
    {
        buttontemp = (Button) gl.getChildAt(i);
        buttontemp.setWidth(idealChildWidth);
    }
}

(The 20 is for the internal and external padding and margins. This could be done more universally, but this is far cleaner)

Then it can be called like this:

    android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout)findViewById(R.id.buttongrid);
    ViewTreeObserver vto = gl.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {@Override public void onGlobalLayout() 
    {

            android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout) findViewById(R.id.buttongrid);
            fillview(gl);

            ViewTreeObserver obs = gl.getViewTreeObserver();
            obs.removeGlobalOnLayoutListener(this);
    }});

It must be done with an observer because we need to wait for the view to be drawn before we call the views.

Community
  • 1
  • 1
dberm22
  • 3,187
  • 1
  • 31
  • 46
0

Please try this code :

Grid.xml :

<GridView
        android:id="@+id/photo_grid"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:numColumns="3" />

Your custom xml file for photo :

<ImageView
        android:id="@+id/img_photo"
        android:layout_width="@dimen/grid_photo"
        android:layout_height="@dimen/grid_photo"
        android:scaleType="fitXY"
        android:layout_margin="5dp"
        android:src="@drawable/ic_launcher" />

NOTE : Here i recommend to use different dimension for image size instead of fixed 92dp. So, by using dimens.xml you can get exact width and height for different resolution also with same space from all side in Gridview.

Mehul Ranpara
  • 4,245
  • 2
  • 26
  • 39
0

I have gone through the same problem a long time ago & get solved by this:

You can do some change attributes as below in Gridview:

<GridView
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/rltop"
        android:fadingEdge="none"
        android:fitsSystemWindows="true"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="3"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:soundEffectsEnabled="true"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp" >
    </GridView>

Get your Screen Size & Width by:

Display  display= ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        myapp.screen_width = display.getWidth(); 
        myapp.screen_height = display.getHeight();

And The Most Important thing:

In your GridAdapter class -> in getView() method:

call below method to target devices with different resolution:

    public void screenResolutions(int screen_width,int screen_height, RelativeLayout relativeLayout)
         {
            if((myapp.screen_width == 240)&&(myapp.screen_height==320))
            {
    //          relativeLayout.getLayoutParams().height=(myapp.screen_height-(35+General.getStatusBarHeight(cntxt)))/3;
                relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
            }
            else if((myapp.screen_width== 720)&&(myapp.screen_height==1280))
            {
      //        relativeLayout.getLayoutParams().height=(myapp.screen_height-(107+General.getStatusBarHeight(cntxt)))/3;
                relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;


            }
            else if((myapp.screen_width== 320)&&(myapp.screen_height==480))
            {
  //            relativeLayout.getLayoutParams().height=(myapp.screen_height-(47+General.getStatusBarHeight(cntxt)))/3;
                relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;


            }
            else if((myapp.screen_width == 480)&&(myapp.screen_height==800))
            {
//              relativeLayout.getLayoutParams().height=(myapp.screen_height-(71+General.getStatusBarHeight(cntxt)))/3;
                relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;


            }
            else if((myapp.screen_width == 768)||(myapp.screen_height==1280))
            {
  //            relativeLayout.getLayoutParams().height=(myapp.screen_height-(114+General.getStatusBarHeight(cntxt)))/3;
                relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;


            }
            else if((myapp.screen_width == 540)&&(myapp.screen_height==960))
            {
    //          relativeLayout.getLayoutParams().height=(myapp.screen_height-(80+General.getStatusBarHeight(cntxt)))/3;
                relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;


            }
            else if((myapp.screen_width == 1080)||(myapp.screen_height==1920))
            {
   //           relativeLayout.getLayoutParams().height=(myapp.screen_height-(160+General.getStatusBarHeight(cntxt)))/3;
                relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;


            }
         }

Where relativelayout = layout which consists ImageView.

You also have to change your height & width of imageview to target multiple resolutions as below:

put this in your imageview:

    android:layout_width="@dimen/image_width"
    android:layout_height="@dimen/image_height"

Put this:

In values folder values-hdpi => dimens.xml(480x800)

<dimen name="image_width">92dp</dimen>
<dimen name="image_height">92dp</dimen>

In values folder values-mdpi => dimens.xml(320x480)

<dimen name="image_width">64dp</dimen>
<dimen name="image_height">64dp</dimen>

In values folder values-sw360dp-notlong-hdpi => dimens.xml(540x960)

<dimen name="image_width">114dp</dimen>
<dimen name="image_height">114dp</dimen>

In values folder values-sw360dp-xhdpi => dimens.xml(720x1280)

<dimen name="image_width">138dp</dimen>
<dimen name="image_height">138dp</dimen>

In values folder values-sw360dp-notlong-xhdpi => dimens.xml(768x1280)

<dimen name="image_width">184dp</dimen>
<dimen name="image_height">184dp</dimen>
Sagar Shah
  • 4,272
  • 2
  • 25
  • 36
  • @Sager I am not sure why you are using screenResolutions() when all the dimens are setting as per dimens.xml secondly if i use above code, i can manage to give equal spaces horizontally but vertically their spaces are not equal – Muhammad Umar Feb 11 '14 at 18:26
  • @MuhammadUmar What screenResolutions() doing is : If you are using resolutions say 480x800 then only 3 images will recover your whole device width i.e. 480 completely by them. That means your device width is perfeclty devided in 3 parts. – Sagar Shah Feb 11 '14 at 18:35
  • yes but the vertical distance is not linear. The horizontal ok. – Muhammad Umar Feb 11 '14 at 18:38
  • For Vertical also you can do the same by uncommenting my height code in sreenresolution() method. – Sagar Shah Feb 11 '14 at 18:41
0

Have you try default demo given by Developer site?

this demo clear shows all the images with equal height and width and with equal space around it.

Please also check this Example for GridView.

Please let me know if its not helping you.

Enjoy Coding... :)

Shreyash Mahajan
  • 23,386
  • 35
  • 116
  • 188