我已经为我的GridView槽Java代码创建了一个BaseAdapter 我希望Gridview中的图像显示如下:
但我目前的代码使图像显示如下:
调整图像大小的代码是:
public class objectAdapter extends BaseAdapter {
private Context context;
private int[] image_id = {R.drawable.banana, R.drawable.kiwi, R.drawable.oatmeal, R.drawable.coconut};
String[] names = {"banana", "kiwi", "oatmeal", "coconut"};
public objectAdapter (Context context){
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView img;
if (convertView == null){
img = new ImageView(context);
img.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
else{
img = (ImageView) convertView;
}
img.setImageResource(image_id[position]);
return img;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public int getCount() {
return image_id.length;
}
}
如果需要,以下是我的MainActivity和activity_main.xml文件:
MainActivity:
public class MainActivity extends Activity {
GridView gridview_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview_id = (GridView) findViewById(R.id.gridview_id);
gridview_id.setAdapter(new objectAdapter(this) );
gridview_id.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
activity_main.xml中:
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:horizontalSpacing="2dp"
android:verticalSpacing="2dp"
android:id="@+id/gridview_id">
如果你知道如何解决这个问题,请告诉我 我真的很感激。