Android RecyclerView设置选中项背景

标签 android android-recyclerview

我正在开发一个 android 应用程序,其中有一个水平 Recyclerview 包含 12 个月名称的文本。当应用程序打开时,当月背景将变为红色。到这里为止,一切都按预期正常工作。 当前行为:每当我选择其他月份名称时,所选月份名称 background color 成功更改为红色,但之前选择的月份名称 background 未更改为白色,它仍然保持在红色。 预期行为:现在,每当我选择其他月份名称时,我都需要将所选月份名称的背景颜色更改为红色,并将之前选择的月份名称背景更改为白色。 下面是我的 recyclerview adapter 类代码:

public class MonthNamesAdapter extends RecyclerView.Adapter<MonthNamesAdapter.MonthNameViewHolder> {

List<MonthNamesModel> monthNamesModelList;
MonthNamesModel monthNamesModel;
Context context;
int lastPosition = -1;
Calendar calendar;
int month, year, date;

String[] monthName = {"January", "February",
        "March", "April", "May", "June", "July",
        "August", "September", "October", "November",
        "December"};
String monthStr;

TextView monthNameTv, numberOfDaysTv;
LinearLayout monthNamesLinearLayout;


public MonthNamesAdapter(List<MonthNamesModel> monthNamesModelList, Context context) {
    this.monthNamesModelList = monthNamesModelList;
    this.context = context;
}

@Override
public MonthNameViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    calendar = Calendar.getInstance();
    month = calendar.get(Calendar.MONTH);
    monthStr = monthName[month];
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.month_name_list, parent, false);

    return new MonthNameViewHolder(view);
}

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


    monthNamesModel = monthNamesModelList.get(position);
    holder.monthNameTv.setText(monthNamesModel.getMonthName());
    holder.numberOfDaysTv.setText(monthNamesModel.getNumberOfDays());
    Log.d("MonthNameAdapter", "onBindViewHolder: Month Number"+month);

    holder.monthNamesLinearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            lastPosition = position;
            notifyDataSetChanged();
        }
    });

    if (lastPosition == position){
        holder.monthNamesLinearLayout.setBackgroundColor(context.getResources().getColor(R.color.app_color));
        holder.numberOfDaysTv.setTextColor(context.getResources().getColor(R.color.colorPrimary));
        holder.monthNameTv.setTextColor(context.getResources().getColor(R.color.colorPrimary));

    }else{
        holder.monthNamesLinearLayout.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary));
        holder.numberOfDaysTv.setTextColor(context.getResources().getColor(R.color.colorBlack));
        holder.monthNameTv.setTextColor(context.getResources().getColor(R.color.app_color));
    }

    if (lastPosition !=position){
        if (month == position){
            holder.monthNamesLinearLayout.setBackgroundColor(context.getResources().getColor(R.color.app_color));
            holder.numberOfDaysTv.setTextColor(context.getResources().getColor(R.color.colorPrimary));
            holder.monthNameTv.setTextColor(context.getResources().getColor(R.color.colorPrimary));

        }
    }

}

@Override
public int getItemCount() {
    return monthNamesModelList.size();
}

public class MonthNameViewHolder extends RecyclerView.ViewHolder {
    TextView monthNameTv, numberOfDaysTv;
    LinearLayout monthNamesLinearLayout;

    public MonthNameViewHolder(View itemView) {
        super(itemView);

        monthNameTv = itemView.findViewById(R.id.monthNameTv);
        numberOfDaysTv = itemView.findViewById(R.id.numberOfDaysTv);
        monthNamesLinearLayout = itemView.findViewById(R.id.monthNamesLinearLayout);

    }
}
}

任何帮助将不胜感激!!! 提前致谢...

最佳答案

试试这个

添加接口(interface)

public interface PositionCallBack {
 void posChanged(int currentPos); //currentPos can also be boolean 
}

在 ModelClass 中添加一个字符串或 bool 值或 int 作为“isSelected”,首先在 MainActivity 中初始化 setIsSelected(“0”)//如果 bool 值设置为 false

在适配器类中

 currentPos=Integer.parseInt(monthNamesModelList.get(position).getIsSelected());
    if (currentPos==1){
        holder.monthNamesLinearLayout.setBackgroundColor(context.getResources().getColor(R.color.colorRed));
    }else {
        holder.monthNamesLinearLayout.setBackgroundColor(context.getResources().getColor(R.color.colorWhite));
    }
    holder.monthNamesLinearLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            for (int i=0;i<monthNamesModelList.size();i++){
                MonthNames monthNames=new MonthNames();
                if (i==position){
                    monthNames.setIsSelected("1");
                }else {
                    monthNames.setIsSelected("0");
                }
                monthNames.setMonthNames(monthStrins[i]);
            }
            notifyDataSetChanged();
            notifyItemChanged(position);
            positionCallBack.posChanged(position);
        }

    });

在主 Activity 中

    monthNamess= new String[]{"January", "February",
            "March", "April", "May", "June", "July",
            "August", "September", "October", "November",
            "December"};

   Calendar calendar = Calendar.getInstance();
    int month = calendar.get(Calendar.MONTH);

    for (int i=0;i< monthNamess.length;i++){
        MonthNames monthNames=new MonthNames();
        if (i==month){

            monthNames.setIsSelected("1");
        }else {
            monthNames.setIsSelected("0");

        }
        monthNames.setMonthNames(monthNamess[i]);
        arrayList.add(monthNames);
    }

  RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(context,
            LinearLayoutManager.HORIZONTAL, false);
    recycler_view.setLayoutManager(mLayoutManager);

    monthNamesAdapter=new MonthNamesAdapter(arrayList,context,this,monthNamess);
    recycler_view.setAdapter(monthNamesAdapter);
    monthNamesAdapter.notifyDataSetChanged();

//这里arrayList是Model类的列表

在MainActivity中实现接口(interface)

 @Override
public void posChanged(int currentPos) {
    arrayList=new ArrayList<>();
    for (int i=0;i<monthNamess.length;i++){
        MonthNames monthNames=new MonthNames();
        if (i==currentPos){

            monthNames.setCurrentPos("1");
        }else {
            monthNames.setCurrentPos("0");

        }
        monthNames.setMonthNames(monthNamess[i]);
        arrayList.add(monthNames);
    }
    monthNamesAdapter=new MonthNamesAdapter(arrayList,context,this,monthNamess);
    recycler_view.setAdapter(monthNamesAdapter);
    monthNamesAdapter.notifyDataSetChanged();
}

关于Android RecyclerView设置选中项背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49973557/

相关文章:

java - Android for 循环不像 java 那样工作

android - Android 中的 OTA 短信

java - 绘制许多像素点 android canvas 或 opengl?

Android-在 onResume() 中获取新位置的最佳方式

java - 如何将数组保存到 PHP 数据库中

android - Base64 图像的 Recyclerview - 滚动缓慢且滞后

android - Espresso - 检查 RecyclerView 商品的订购是否正确

android - 从 firebase 数据库的 recyclerview 中点击子项获取父键值

java - Android RecyclerView 固定页脚

android - 如何从特定索引开始ArrayList?