我正在努力做到这一点
虽然我在 GridView 中有项目,但我想要项目的大小/颜色像图片中的那样。
这是我的代码
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageButton imageView;
if (convertView == null) {
imageView = new ImageButton(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else
{
imageView = (ImageButton) convertView;
}
imageView.setImageResource(mThumbIds[position]);
imageView.setBackgroundColor(mThumbIds[0].);
return imageView;
}
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.town_hall1,
R.drawable.town_hall2,
R.drawable.town_hall3,
R.drawable.town_hall4,
R.drawable.town_hall5,
R.drawable.town_hall6,
R.drawable.town_hall7,
R.drawable.town_hall8,
R.drawable.town_hall9,
R.drawable.town_hall10,
R.drawable.town_hall11,
};
}
我是初学者,请提供构建该布局的步骤。 谢谢
最佳答案
如果您在 mThumbIds
中有虚拟数据,那么您可以在 getView()
中使用 switch case,如下所示:
public View getView(int position, View convertView, ViewGroup parent) {
ImageButton imageView;
if (convertView == null) {
switch(position){
case 1:
imageView = new ImageButton(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(10, 10, 10, 10);
imageView.setImageResource(mThumbIds[1]);
imageView.setBackgroundColor(mThumbIds[0].);
break;
case 2:
imageView = new ImageButton(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageResource(mThumbIds[2]);
imageView.setBackgroundColor(mThumbIds[0].);
break;
case 3:
imageView = new ImageButton(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(50, 50));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5)
imageView.setImageResource(mThumbIds[3]);
imageView.setBackgroundColor(mThumbIds[0].);
break;
}
}
else
{
imageView = (ImageButton) convertView;
}
return imageView;
}
您可以使用与图像数量相等的案例数量。您为不同的图像设置了不同的属性。
关于android - 如何实用地为每个 GridView 项目设置不同的颜色/背景/高度/宽度等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41568133/