gpt4 book ai didi

android - 显示重复项的 GridView

转载 作者:行者123 更新时间:2023-11-29 19:10:31 27 4
gpt4 key购买 nike

我真的很惊讶,代码发生了什么,gridView 项目每次都在第 11 位显示重复,有时也显示在第 12 位。

enter image description here

您可以看到“桌面”网格已填充两次。

常量文件中的网格图标和名称

public static final String[] values = {
DESKTOP,
LAPTOP,
SERVER,
PRINTER,
NETWORK_SUPPORT,
AIR_CONTITION,
CCTV_CAMERA,
ALL_IN_ONE_PC,
HOME_CLEANING,
APPLICANCE_REPAIR,
ELECTRICITY,
PLUMBING
};

public static final int[] images = {
R.drawable.desktop_pc_icon,
R.drawable.laptop_pc_icon,
R.drawable.server_icon,
R.drawable.printer_icon,
R.drawable.network_support_icon,
R.drawable.aircondition_icon,
R.drawable.cctv_camera_icon,
R.drawable.all_in_one_pc_icon,
R.drawable.home_cleaning_icon,
R.drawable.appliance_repair_icon,
R.drawable.electrical_icon,
R.drawable.plumbing_icon
};

Grid Adopter设置(在onCreate方法中)

 final GridView mainGrid = (GridView) findViewById(R.id.main_grid);
mainGrid.setAdapter(new GridAdapter(MainActivity.this, AppConstants.productsId, AppConstants.values, AppConstants.images));

网格适配器

public class GridAdapter extends BaseAdapter {

private final String[] productsId;
private final String[] values;
private final int[] images;
private Context context;
private LayoutInflater layoutInflater;

public GridAdapter(final Context context, final String [] productsId, final String[] values, final int[] images) {
this.context = context;
this.productsId = productsId;
this.values = values;
this.images = images;
}

@Override
public int getCount() {
return productsId.length;
}

@Override
public Object getItem(final int i) {
return values[i];
}

@Override
public long getItemId(final int i) {
return 0;
}

@Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = layoutInflater.inflate(R.layout.single_grid_item, null);

//Grid Text
final TextView gridText = view.findViewById(R.id.grid_text);
gridText.setText(values[i]);

//Grid Image
final ImageView gridImage = view.findViewById(R.id.grid_image);
gridImage.setImageResource(images[i]);
}
return view;
}
}

最佳答案

像下面这样更改您的 getView,您应该在每次调用 getView 时更新该项目,但在您的情况下,您仅在 View 为 null 时才更新。所以这个问题的发生是因为重用了 View 。

@Override
public View getView(final int i, View view, final ViewGroup viewGroup) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = layoutInflater.inflate(R.layout.single_grid_item, null);


}

//Grid Text
final TextView gridText = view.findViewById(R.id.grid_text);
gridText.setText(values[i]);

//Grid Image
final ImageView gridImage = view.findViewById(R.id.grid_image);
gridImage.setImageResource(images[i]);
return view;
}

关于android - 显示重复项的 GridView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45532459/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com