1

目前我DataBinding在我的应用程序中使用它,它就像魅力一样工作。现在我有一个问题,我们可以根据 API 响应创建多个复选框吗?

就像ArrayList我的模型类中有一个,无论该数组列表的大小是多少,都应该添加很多复选框。

{"hobby": [
  {
    "id": "1",
    "hobby": "Sports"
  },
  {
    "id": "2",
    "hobby": "Hangout"
  },
  {
    "id": "3",
    "hobby": "Skydiving"
  },
  {
    "id": "4",
    "hobby": "Scubadiving"
  },
  {
    "id": "5",
    "hobby": "Travelling"
  }
]}

现在我想创建所有爱好的复选框,并想检索选定复选框的值。

谁能帮我这个?

我为此创建了 BindingAdapter,并且能够创建复选框运行时

@BindingAdapter({"bind:values"})
public static void createCheckboxes(LinearLayout layout, UserModel model) {
    List<UserModel.Hobby> list = model.getHobby();
    for (int i = 0; i < list.size(); i++) {
        CheckBox chk = new CheckBox(layout.getContext());
        chk.setText(list.get(i).getHobby());
        layout.addView(chk);
    }
}

现在的问题是如何获取选定的复选框值。

注意:需要用 DataBinding 来实现。

4

2 回答 2

0

Finally have done it, don't know whether it's correct use of databinding or not.

created binding method like this

@BindingAdapter({"bind:values"})
public static void createCheckboxes(LinearLayout layout, UserModel model) {
   List<UserModel.Hobby> list = model.getHobby();
   for (int i = 0; i < list.size(); i++) {
      CheckBox chk = new CheckBox(layout.getContext());
      chk.setText(list.get(i).getHobby());

      final int finalI = i;
      chk.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    UserModel.Hobby model=list.get(finalI);
                    if(model.isSelected())
                        model.setSelected(false);
                    else
                        model.setSelected(true);
                    list.set(finalI,model);
                    layout.invalidate();
                }
      });

      layout.addView(chk);
   }
}

and in my xml, created one LinearLayout

<LinearLayout
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:layout_marginLeft="15dp"
     app:values="@{user}"/>

and while saving data, i am just checking with use of for loop and got which values are selected.

for (int i = 0; i < list.size(); i++) {
    if(list.get(i).isSelected())
                    Log.e("", "selected: " + list.get(i).getHobby());
 }
于 2016-05-17T13:08:26.287 回答
-1

这个怎么样 :

LinearLayout root= (LinearLayout)findViewById(R.id.test);
// use loop 
CheckBox checkBoxOne = new CheckBox(this);
root.addView(checkBoxOne);
于 2016-05-17T04:49:08.060 回答