gpt4 book ai didi

Android ViewHolder 背景颜色

转载 作者:行者123 更新时间:2023-11-29 14:30:51 28 4
gpt4 key购买 nike

我正在创建一个 Android 应用程序,其中包含一个带有嵌套 CardView 的 RecyclerView。我需要将所有其他卡片替换为不同的颜色。我正在使用 @Override 来覆盖 onBindViewHolder(ViewHolder vh, int pos) 方法。我需要通过该方法更改背景颜色(我假设),但是没有设置 ViewHolder 背景颜色的方法!

对不起我的菜鸟,我现在正在学习Android开发。

-本

编辑:代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_9);

pieRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
pieRecyclerView.setHasFixedSize(true);
pies = makePies();

pieLayoutManager = new LinearLayoutManager(this);
pieRecyclerView.setLayoutManager(pieLayoutManager);
PieAdapter adapter = new PieAdapter(pies);
pieRecyclerView.setAdapter(adapter);
}

public class PieAdapter extends RecyclerView.Adapter<ViewHolder> {

Context mContext;
ArrayList<Pie> mPies;
LayoutInflater mInflater;

public PieAdapter(ArrayList<Pie> pies) {

mPies = pies;

}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
return new ViewHolder(v);

}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

Pie currentPie = mPies.get(position);
holder.textViewName.setText(currentPie.mName);
holder.textViewDescription.setText(currentPie.mDescription);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String price = formatter.format(currentPie.mPrice);
holder.textViewPrice.setText(price);

}

@Override
public int getItemCount() {

return mPies.size();

}
}

private class ViewHolder extends RecyclerView.ViewHolder {

public TextView textViewName;
public TextView textViewDescription;
public TextView textViewPrice;

public ViewHolder(View v) {

super(v);
textViewName = (TextView) v.findViewById(R.id.textViewName);
textViewDescription = (TextView) v.findViewById(R.id.textViewDescription);
textViewPrice = (TextView) v.findViewById(R.id.textViewPrice);

}
}

private ArrayList<Pie> makePies() {

ArrayList<Pie> pies = new ArrayList<Pie>();
pies.add(new Pie("Apple", "An old-fashoned favorite.", 1.5));
pies.add(new Pie("Blueberry", "Made with fresh Maine blueberries.", 1.5));
pies.add(new Pie("Cherry", "Delicious and fresh made daily", 2.0));
pies.add(new Pie("Coconut Cream", "A customer favorite.", 2.5));
return pies;

}

private class Pie {

String mName;
String mDescription;
double mPrice;

public Pie(String name, String description, double price) {

this.mName = name;
this.mDescription = description;
this.mPrice = price;

}
}`

最佳答案

ViewHolder 对象本身不是一个View。如果您想更改整个列表项的背景,您可能需要调用 viewHolder.itemView.setBackgroundColor(...)ViewHolderitemView 是您传递给构造函数的任何 View

关于Android ViewHolder 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33793853/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com