为了账号安全,请及时绑定邮箱和手机立即绑定

Android中如何将ArrayList的所有元素显示为Chips

Android中如何将ArrayList的所有元素显示为Chips

元芳怎么了 2023-09-20 16:29:14
我有一个ArrayList<String>这样的[Angularjs, JavaScript, Css]在我的适配器中,我ArrayList从另一个意图获取标签。我尝试使用以下方法显示ArrayListas Chips的所有元素,但我只得到 ArrayList 的最后一个元素。我只看到一个带有 ArrayList 最后一个元素的 Chip。for (String tag: card.getTags()) {   Log.d(TAG, "tag - " + tag);   holder.tags.setText(tag); }谁能指导一下,我如何更改代码以将 ArrayList 的所有元素显示为Chips.
查看完整描述

2 回答

?
HUH函数

TA贡献1836条经验 获得超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);

  }


查看完整回答
反对 回复 2023-09-20
?
互换的青春

TA贡献1797条经验 获得超6个赞

目前,您正在更换支架的环路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());

}


查看完整回答
反对 回复 2023-09-20
  • 2 回答
  • 0 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信