4

我有一个ArrayList<String>这样的[Angularjs, JavaScript, Css]

在我的适配器中,我ArrayList从另一个 Intent 获取标签。我尝试使用以下方法显示ArrayList作为芯片的所有元素,但我只得到了 ArrayList 的最后一个元素。我只看到一个带有 ArrayList 的最后一个元素的芯片。

for (String tag: card.getTags()) {
  Log.d(TAG, "tag - " + tag);
  holder.tags.setText(tag);
}

谁能指导一下,如何更改我的代码以将 ArrayList 的所有元素显示为Chips.

4

2 回答 2

4

如果你在谈论芯片

在 xml 布局中添加ChipGroup要显示筹码的位置

<com.google.android.material.chip.ChipGroup
 android:id="@+id/chipGroup"
 android:layout_width="match_parent"
 app:chipSpacingVertical="2dp"
 android:layout_height="wrap_content"/>

现在您可以使用此方法添加您的 ArrayList,如下Chip所示ChipGroup

private void addChip(String pItem, ChipGroup pChipGroup) {
    Chip lChip = new Chip(this);
    lChip.setText(pItem);
    lChip.setTextColor(getResources().getColor(R.color.primary_text));
    lChip.setChipBackgroundColor(getResources().getColorStateList(R.color.chip_bg));

    pChipGroup.addView(lChip, pChipGroup.getChildCount() - 1);
  }
于 2019-10-03T03:26:19.140 回答
2

目前,您正在更换支架tagsforEach循环。您只有一个持有者并不断更新,直到循环结束;这就是你坚持下去的原因chip/tag

如果您指的是 MaterialComponents 的ChipGroup

ChipGroup chipGroup = new ChipGroup(parentView.getContext());

String[] genres = {"Thriller", "Comedy", "Adventure"};
for(String genre : genres) {
   Chip chip = new Chip(parentView.getContext());
   chip.setText(genre);
   chipGroup.addView(chip);
}

我假设您必须使用RecyclerView我在您的代码段中看到的持有人。

以下是视图层次结构;我假设您正在努力实现;如果不是,那么您可以使用相同的逻辑线来移动这些部分

  • 回收站视图
    • 每个项目/视图
      • 标签 - 使用FlowLayout多个标签 - 在视图中添加多个标签

您需要bindRecyclerView 中的每个项目。

@Override
public void onBindViewHolder(final YourViewHolder holder, final int position) {
    ...
    // assuming you have FlowLayout in recyclerview view item
    // do add holder pattern to flowlayout as well
    fillAutoSpacingLayout(card.getTags(), holder.flowLayout);
}

这里我使用FlowLayout在 RecyclerView 的每个视图中添加芯片或标签。

在 onBindViewHolder 中绑定每个项目/视图:

private void fillAutoSpacingLayout(ArrayList<String> tags, FlowLayout flowLayout) {

    for (String tag : tags) {
        TextView textView = buildLabel(tag);
        flowLayout.addView(textView);
    }
}

private TextView buildLabel(String text) {
    TextView textView = new TextView(this);
    textView.setText(text);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    textView.setPadding((int)dpToPx(16), (int)dpToPx(8), (int)dpToPx(16), (int)dpToPx(8));
    textView.setBackgroundResource(R.drawable.label_bg);

    return textView;
}

private float dpToPx(float dp){
    return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}

此外,您可以参考这个SO question,因为它在同一行。

于 2019-10-03T03:23:51.397 回答