我将创建一个GridView以展示图片。即使我设置了垂直和水平间距,图片仍然会重叠在一起。这是为什么?如何解决这个问题?您可以在图像中看到这一点。
我的代码:
这是我得到的输出结果。
我的代码:
public class Images extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.images);
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
int width, height;
public Integer[] mThumbIds = {
R.drawable.radhe, R.drawable.radhe,
R.drawable.radhe, R.drawable.radhe,
R.drawable.radhe, R.drawable.radhe,
R.drawable.radhe, R.drawable.radhe,
R.drawable.radhe
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
@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);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
width = displaymetrics.widthPixels;
height = displaymetrics.heightPixels;
imageView.setLayoutParams(new GridView.LayoutParams(width/3, height/3));
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="3"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="5dp"
android:gravity="center"
android:stretchMode="columnWidth" >
</GridView>
这是我得到的输出结果。
![enter image description here](https://istack.dev59.com/UjJS8.webp)
ImageView
的宽度和高度。你在这里硬编码了new GridView.LayoutParams(width/3, height/3)
。 - Gopal Gopinew GridView.LayoutParams(GridView.LayoutParams.WRAP_CONTENT,GridView.LayoutParams.WRAP_CONTENT)
和android:columnWidth="90dp"
。 - Gopal GopiGridView
的宽度而不是屏幕宽度。在计算宽度时需要考虑水平间距,不要硬编码高度,将其设置为WRAP_CONTENT
。 - Gopal Gopi