【问题标题】:What type of array do I use if I want to set the size of the array and I want nulls in the empty spots如果我想设置数组的大小并且我想在空白处使用空值,我应该使用什么类型的数组
【发布时间】:2018-03-10 12:28:07
【问题描述】:

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

【问题讨论】:

    标签: java android arrays listview android-adapter


    【解决方案1】:

    我想使用一种具有固定大小的数组(所以我需要自己设置大小),但我不希望数组中的空白点被丢弃,我希望它们为空。

    每个 Java 数组都有一个固定长度,必须在声明时提供。另外,如果是引用类型的数组,则默认值null。所以,

    String[] arr = new String[1];
    

    创建一个有足够空间存储单个String 的数组。并且默认值是null,因此

    System.out.println(arr[0]);
    

    输出

    null
    

    【讨论】:

    • 是的,但是,如果我尝试为数组设置一个默认大小被覆盖的资源,那么该解决方案将无法工作。
    • 不要为数组设置资源。或者更确切地说,为临时数组设置资源,然后以编程方式将值复制到另一个。
    • 谢谢。我这样做的方式如下:String[] itemLinks = new String[itemNames.length]; String[] temp = getResources().getStringArray(R.array.catImages); System.arraycopy(temp, 0, itemLinks, 0, temp.length);
    猜你喜欢
    • 2022-01-12
    • 2022-08-14
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多