I want to create a simple android wallpaper app just for practice. So I added pictures to an assets folder, and I want to show them in a gridview. I created it, but for some reason the pictures in the gridview doesn't appear in squares rather in a large height format. I'm attaching my code if anyone can see where the problem is:
this is how it looks like:
you can see that it creates rectangles instead of equal squares.
MainActivity:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
}
ImageAdapter:
public class ImageAdapter extends BaseAdapter {
private Context context;
private String[] list;
public ImageAdapter(Context c) {
context = c;
try {
list = context.getAssets().list("imgs");
} catch (IOException e) {
e.printStackTrace();
}
}
public int getCount() {return list.length;}
public Object getItem(int position) {return null;}
public long getItemId(int position) {return 0;}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView img;
if (convertView == null) {
img = new ImageView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
img.setLayoutParams(new GridView.LayoutParams(params));
img.setScaleType(ImageView.ScaleType.CENTER);
img.setPadding(8, 8, 8, 8);
} else {
img = (ImageView) convertView;
}
try {
InputStream ims = context.getAssets().open("imgs/" + list[position]);
Bitmap bitmap = BitmapFactory.decodeStream(ims);
img.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
}
and this is the xml layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<GridView
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</android.support.constraint.ConstraintLayout>