子数组列表输出在n个元素之后重复自身

问题描述 投票:0回答:2

[新手。我正在编写一个测验应用程序full code on Github,该应用程序使用四个参数加载arrayList

  1. 问题
  2. 图像(来自可绘制对象)
  3. 关键答案
  4. 在radioGroup(sub-arrayList)中显示的可能答案

来自下面的strings.xml

    ...
    <string name="questionOne">Who is the "Modern Love" rock star singer?</string>
    <string name="answerOne">David Bowie</string>

    <string-array name="celebrityOne">
        <item>Jaimie Hendrix</item>
        <item>David Bowie</item>
        <item>Jim Morrison</item>
        <item>Elvis Presley</item>
    </string-array>
    ...

下面是如何在MainActivity中加载参数(第三个参数是子数组列表)

    ArrayList<Object> arrayList = new ArrayList<>();
    loaddata()

    ...

    public void loadData() {
        arrayList.add(new Quiz(getResources().getString(R.string.questionOne), 
                getResources().getDrawable(R.drawable.celebrity_one_image, null), 
                new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.celebrityOne))),
                getResources().getString(R.string.answerOne)));   

        arrayList.add(new Quiz(getResources().getString(R.string.questionTwo), 
                getResources().getDrawable(R.drawable.celebrity_two_image, null), 
                new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.celebrityTwo))),
                getResources().getString(R.string.answerTwo)));

        ...  

    }

问题是经过N次迭代后,sub-arrayList开始重复自身(请参见下图)。

[另外,我认为问题的根源可能在适配器中,在该适配器中,子数组中的每个字符串都分配给一个radioButton


      void createRadioButtons(String[] arrayAnswer) {
            if (mRadioGroup.getChildAt(0) != null)
                return;
            for (int i = 0; i < arrayAnswer.length; i++) {
                mRadioGroup.addView(createRadioButtonAnswerAndSetOnClickListener(arrayAnswer[i]));
            }
        }

        RadioButton createRadioButtonAnswerAndSetOnClickListener(String string) {
            RadioButton radioButton = new RadioButton(mContext);
            radioButton.setText(string);
            radioButton.setOnClickListener(this);
            return radioButton;
        }

[First Image Second image

我的情况可能类似于this,但是我没有静态字段,并且arrayList初始化为new,所以不需要clear()

java android arraylist
2个回答
0
投票

来自Documentation

RecyclerView仅创建显示动态内容的屏幕部分所需的视线支架,外加一些视线支架。当用户滚动浏览列表时,RecyclerView会获取屏幕外的视图,并将它们重新绑定到正在滚动到屏幕上的数据。

这意味着RecyclerView在滚动时会重复使用已创建的视图持有人(这就是重复数据的原因),并且必须用新数据重新填充视图。因此,当您从createRadioButtons方法中返回时,必须从mRadioGroup.getChildAt(0) != null中将RadioButtons文本更改为新数据,而不是从arrayAnswer方法返回。


0
投票

在您的适配器中只需更改此:

© www.soinside.com 2019 - 2024. All rights reserved.