目前,您正在更换支架tags
的forEach
循环。您只有一个持有者并不断更新,直到循环结束;这就是你坚持下去的原因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
多个标签 - 在视图中添加多个标签
您需要bind
RecyclerView 中的每个项目。
@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,因为它在同一行。