【问题标题】:Recyclerview add radiobutons programmaticallyRecyclerview 以编程方式添加单选按钮
【发布时间】:2018-01-15 12:12:18
【问题描述】:

我正在使用 Java 创建一个 Android 应用程序,它会显示一个问题和 3 或 4 个选项(MCQ 应用程序)。我在 XML 中使用了带有 TextView 的 RecyclerView 来保存问题。

但是,我对如何为选项部分创建单选按钮/复选框感到困惑,因为它们是动态的。这意味着,根据数据库中的条目,一个问题可能具有从 1 到 6 的任意数量的单选按钮选项。此外,根据数据库条目,很少有问题可能再次具有复选框而不是单选按钮。

由于这些是在运行时决定的,因此我无法将这些单选按钮/复选框保留在 XML 文件中。最初我尝试在 onBindViewHolder 方法中创建它们,但这样做会显着减慢滚动速度,因为即使在滚动时也会调用此方法。由于这是一个非常常见的用例,我相信框架必须有现成的解决方案,我还没有发现。

我不想添加所有可能的单选按钮/复选框并在运行时使用它们的可见性。

【问题讨论】:

  • 首先了解 recyclerView 的工作原理并查看此链接以获取帮助 - zoftino.com/android-recyclerview-radiobutton
  • @Sanjay 我确实收集了对 RecyclerView 的一些基本了解,并且您链接中的示例讨论了单个 RadioButton 对吗?但是我的用例有所不同,我只在运行时才知道 RadioButton 的数量。所以我不能在 XML 中添加它们。

标签: android performance android-recyclerview


【解决方案1】:

您可以将 xml 文件创建为 -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="Question Text " />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp" />

</LinearLayout>

在你的适配器中让你有问题的数组列表说

ArrayList<Question> queList;

问题实例包含

class Question{
String question;
int nubOfOptions;
String[] options;
int selectedOption = 0;
}

现在先取ViewHolder中radioGroup的id为-

RadioGroup radioGroup = (RadioGroup)view.findViewById(R.id.radioGroup);

现在在 onBindViewHolder 中你可以这样做 -

onBindViewHolder(int position, ....){
  Question que = queList.get(position);
  radioGroup.removeAllViews();
  for(int count=0; count<radioBtnCount;count++){

       RadioButton btn= new RadioButton(context);
       btn.setText("you option");
       if(selectedOption==count+1){
        btn.setCheck(true);
        }
       radioGroup.addView(btn);


    }
}

您必须删除所有视图,否则滚动时会遇到问题。

【讨论】:

  • 我已经尝试过类似的事情,但没有 RadioGroup。我不能使用 RadioGroup,因为我希望每行只有两个 RadioButton,如果我使用 RadioGroup,这是不可能的。相反,我只在 TableLayout 中创建了 RadioButtons,然后为同一问题取消选择其他 RadioButtons。这种方法的问题是,由于 onBindViewHolder 方法在上下滚动时也会被调用,这会成为一种昂贵的操作并减慢滚动操作。但是,正如您所建议的,我可以尝试使用 RadioGroup 看看性能是否有所提高。
猜你喜欢
  • 1970-01-01
  • 2018-05-21
  • 2013-05-02
  • 2012-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
相关资源
最近更新 更多