我想使用一种具有固定大小的数组(因此我需要自己设置大小),但我不想丢弃数组中的空白点,我希望它们只是空值。 基本上我有一个用图片和文本填充 ListView 的适配器。我使用两个字符串数组 (fragment) 获取文本和图片链接:
String[] itemNames = getResources().getStringArray(R.array.catItems);
String[] itemLinks = getResources().getStringArray(R.array.catLinks);
mMenuItems = findViewById(R.id.menuItems);
mMenuItems.setAdapter(new MenuCatAdapter(this, itemLinks, itemNames));
我想将 itemLinks 数组的长度设置为与 itemNames 数组的长度相同。在 MenuAdapter 中,我在 getView() 方法中使用以下代码来设置 ListView (fragment) 的文本和图像:
public View getView(int position, View convertView, ViewGroup parent) {
View customView = convertView;
LayoutInflater layoutInflater;
ViewHolder holder = new ViewHolder();
if(customView == null) {
layoutInflater = LayoutInflater.from(mActivity.getApplicationContext());
customView = layoutInflater.inflate(R.layout.nav_cat_list_item, parent, false);
holder.itemImage = customView.findViewById(R.id.navCatImageView);
holder.itemName = customView.findViewById(R.id.navCatTextView);
customView.setTag(holder);
} else {
holder = (ViewHolder) customView.getTag();
}
// Set the image
if(mImageLinks[position] == null) { //What to do if the link is non-existent
Glide .with(mActivity.getApplicationContext())
.load(R.drawable.sidebar_sandwich)
.into(holder.itemImage);
} else {
Glide .with(mActivity.getApplicationContext())
.load(mImageLinks[position])
.into(holder.itemImage);
}
holder.itemImage.setContentDescription(mItemNames[position]);
// Set the text
holder.itemName.setText(mItemNames[position]);
return customView;
}
我想确保即使我没有图像链接(因此链接为空),我仍然得到占位符图像(或没有图像),而不是得到 ArrayOutOfBoundsException。
最佳答案
I want to use a type of array that has a set size (so I need to set the size myself) but I don't want the empty spots in the array to be discarded, I want them to just be null.
每个 Java 数组都有固定长度,必须在声明时提供。此外,如果它是一个引用类型的数组,那么默认值是 null
。所以,
String[] arr = new String[1];
创建一个有足够空间存储单个 String
的数组。由于这个原因,默认值为 null
System.out.println(arr[0]);
输出
null
关于java - 如果我想设置数组的大小并且我想在空白处使用空值,我应该使用什么类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49209079/