java - 如果我想设置数组的大小并且我想在空白处使用空值,我应该使用什么类型的数组

标签 java android arrays listview android-adapter

我想使用一种具有固定大小的数组(因此我需要自己设置大小),但我不想丢弃数组中的空白点,我希望它们只是空值。 基本上我有一个用图片和文本填充 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/

相关文章:

java - 一段时间后检查 NFC 是否仍然启用

android - AsyncTask不会在Android 2.3 Andengine中引发异常

android - 我需要帮助以将按照我的 'Document' 列表排序的 'Collection' 数据显示到 RecyclerView 中(检索到的数据未按照列表排序,#AskFirebase)

arrays - 如何在 ASSOCIATE block 中保留 Fortran 数组边界?

Java 堆栈与队列性能

java - Apache oltu Oauth2 token 验证

c++ - 从input1查找input2中字符的位置

arrays - 访问和搜索有什么区别? (确定数组的时间复杂度时)

java - 基本的 Java 线程问题

android - Dagger2 在 View 模型中注入(inject)导航器