Caroline
Caroline

Reputation: 381

Rectangular images in GridView

How can I create a GirdView in which the images are rectangular (120 x 58.5), which would result in a non square cell? Currently if I have this XML layout there is whitespace above and below the image because the cell is 120 x 120. The width of each cell should be 120 and the height 58.

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/AppsOverviewGrid"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:columnWidth="120dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="0dp"
    android:horizontalSpacing="8dp"
    android:stretchMode="columnWidth"
    android:gravity="center">
</GridView>

Thanks for the help.

Upvotes: 2

Views: 2823

Answers (2)

netsuvi
netsuvi

Reputation: 26

the easiest aproach for this is just to set the width and height of the imageview in the adapter.

public class ImageAdapter extends BaseAdapter {

 // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(120, 58));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(pictureArray[position]);

        return imageView;
    }

   // references to our images
    private Integer[] pictureArray= {
            R.drawable.pic1, R.drawable.pic2,
     }

}

Then set the Adapter to the gridview.

 GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));

Upvotes: 0

Korhan Ozturk
Korhan Ozturk

Reputation: 11308

In my opinion, ideal solution is to create a layout file for the items in gridview layout in which you can specify the height of the images (using an ImageView). Then you can use a custom adapter with LayoutInflater to connect your grid view items with your main layout.

Here is a great tutorial for that (2. example): http://www.mkyong.com/android/android-gridview-example/

Upvotes: 2

Related Questions