lasthope
lasthope

Reputation: 23

set Image View height and width in Grid View

i want to create a image gallery in my app

i use grid view to display images , but images displaying Messed up

how i can display images equal ?such as other image gallery app

layout file :

<GridView
        android:id="@+id/galleryGridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:numColumns="3"
        android:rowCount="3"
        android:stretchMode="columnWidth"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp" />

java file:

public class GalleryManager extends BaseAdapter {
    Context context;
    List<Drawable> list;

    public GalleryManager(Context context , List<Drawable> list ) {
        this.context = context;
        //this.list = list;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        try {
            ImageView imageView = new ImageView(context);
            imageView.setImageDrawable(list.get(position));
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            return imageView;
        }
            catch(Exception e){
                Log.i("Tag", "getView: "+e.toString());
            }
            return null;
    }
}

Upvotes: 0

Views: 782

Answers (2)

Nguyễn Trung Hiếu
Nguyễn Trung Hiếu

Reputation: 2032

Try

public class MyImageView extends android.support.v7.widget.AppCompatImageView {
public MyImageView(Context context) {
    super(context);
}

public MyImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyImageView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   // super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int size = getContext().getResources().getDimensionPixelSize(R.dimen.space);
    setMeasuredDimension(size, size);
}
}

in dimen.xml

<dimen name="space">100dp</dimen>

And

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    try {
        MyImageView imageView = new MyImageView(context);
        imageView.setImageDrawable(list.get(position));
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        return imageView;
    }
        catch(Exception e){
            Log.i("Tag", "getView: "+e.toString());
        }
        return null;
}
}

Upvotes: 2

Yunus Kulyyev
Yunus Kulyyev

Reputation: 1022

Try setting the image weight to 1 in your java code

Upvotes: 0

Related Questions