我有一个具有recyclerview的应用程序。我想给用户一个机会,在夜间和白天模式主题之间切换。我知道如何更改文本颜色和背景颜色,但是在这种情况下我不能。实际上,我无法从MainActivity中找到项目布局变量。如何从MainActivity创建ViewHolder类的对象?谁能帮我吗?
这是我的适配器类:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private List<ListItemModel> listItems;
private Context context;
public MyAdapter(List<ListItemModel> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_model, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final ListItemModel listItem = listItems.get(position);
holder.index_number.setText(listItem.getIndexNumber());
holder.title_name.setText(listItem.getTitle());
}
@Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView index_number, title_name;
public ViewHolder(View itemView) {
super(itemView);
index_number = (TextView) itemView.findViewById(R.id.model_text_index_id);
title_name = (TextView) itemView.findViewById(R.id.model_text_title_id);
}
}
}
答案 0 :(得分:0)
如果是一个选择列表,则可以在列表中定义一个int
参数,并在适配器中定义一个方法
....
private int selectedPosition = -1;
public void setSelectedPosition(int index){
selectedPosition = index;
notifyItemChanged(selectedPosition)
}
然后在OnBindViewHolder
中执行以下操作:
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final ListItemModel listItem = listItems.get(position);
holder.index_number.setText(listItem.getIndexNumber());
holder.title_name.setText(listItem.getTitle());
if(position == selectedPosition){
holder.index_number.setTextColor(MY_COLOR)
holder.title_name.setTextColor(MY_COLOR)
} else {
holder.index_number.setTextColor(NORMAL_COLOR)
holder.title_name.setTextColor(NORMAL_COLOR)
}
}
对于多选列表,您可以在ListItemModel
中定义一个像isChosen这样的参数,并将该参数更改为true和false,然后在OnBindViewHolder
中检查该参数
答案 1 :(得分:0)
i found the solution of your problem
create a method inside your activity and call when click on item in adapter and send position
public void click(int position){
TestAdapter.ViewHolder viewHolder = (TestAdapter.ViewHolder)recyclerView.findViewHolderForAdapterPosition(position);
viewHolder.text_color .setTextColor(Color.parseColor("#245251"));
}
hope this will help you.