我正在创建一个带有RecyclerView
. 每个列表项都是来自用户的帖子(现在是硬编码)。每篇文章的背景都是从layer-list
可绘制文件夹中的 XML 文件加载的。
一切都按预期使用文本等,但我正在尝试以编程方式更改背景颜色。它改变了每个项目的背景颜色,除了第一个项目,我不知道为什么。
第一项总是获取XML 文件中调用solid
的shape
内部颜色指定的背景颜色,因此不会更改,但以下各项获取颜色。item
shape_background
#ff22ff
这是适配器的实现:
class PostListAdapter extends RecyclerView.Adapter<PostListAdapter.PostViewHolder>{
private LayoutInflater inflater;
private List<PostRow> data = Collections.emptyList();
PostListAdapter(Context context, List<PostRow> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
PostRow current = data.get(position);
holder.text.setText(current.text.toUpperCase());
holder.time.setText(current.time.toUpperCase());
holder.answers.setText(current.answers.toUpperCase());
try {
// "#ff22ff" will be changed to current.color, unique color for every post
// That string is parsed from a JSON request, hence the try-catch.
int color = Color.parseColor("#ff22ff");
holder.shape.setColor(color);
} catch (Exception e){
e.printStackTrace();
}
}
@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.post_row, parent, false);
return new PostViewHolder(view);
}
@Override
public int getItemCount() {
return data.size();
}
class PostViewHolder extends RecyclerView.ViewHolder {
TextView text;
TextView time;
TextView answers;
GradientDrawable shape;
PostViewHolder(View itemView) {
super(itemView);
text = (TextView) itemView.findViewById(R.id.text);
time = (TextView) itemView.findViewById(R.id.time);
answers = (TextView) itemView.findViewById(R.id.answers);
LayerDrawable layers = (LayerDrawable) ContextCompat.getDrawable(itemView.getContext(), R.drawable.bubble);
shape = (GradientDrawable) (layers.findDrawableByLayerId(R.id.shape_background));
}
}
}
为什么第一项的背景没有改变,而文本却改变了?
先感谢您!