Android RecyclerView设置所选项目背景

时间:2018-04-23 04:46:41

标签: android android-recyclerview recycler-adapter

我正在开发一个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);

    }
}
}

任何帮助都会非常感激!!! 提前谢谢......

5 个答案:

答案 0 :(得分:0)

试试这个:

@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);

        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));
        }
        holder.monthNamesLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                notifyDataSetChanged();
            }
        });

答案 1 :(得分:0)

可能是你可以在名为isSelected的'MonthNamesModel'中添加一个布尔变量

这将有助于维护您所需要的只需在onBindViewHolder中检查该变量

  if(monthNamesModel .getIsSelected())
   {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));
 }

并在

中更改该变量
   holder.monthNamesLinearLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

      if( monthNamesModel .getIsSelected())
      {
      monthNamesModelList.get(position).setIsSelected(false);
      monthNamesModel .setIsSelected(false);
      }
      else
      {
      monthNamesModelList.get(position).setIsSelected(true);
      monthNamesModel .setIsSelected(true) ;
      }
        notifyDataSetChanged();
    }
});

答案 2 :(得分:0)

将默认属性设置为视图,并在该位置满足条件时更改属性:

    //set a default property sot not selected state
    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 position satisfy you condition then set property for selected state.
    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 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));
    }

我认为这种方式你不必考虑复杂的方式。

修改

如果您最初将calendar.get(Calendar.MONTH);值分配给lastPosition,则可以使其更简单。然后,如果这不会破坏您的业务逻辑,您可以忽略month == position这个条件。

答案 3 :(得分:0)

试试这个

添加界面

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

在ModelClass中添加一个字符串或boolean或int作为&#34; isSelected&#34;,在MainActivity中初始化第一个setIsSelected(&#34; 0&#34;)//如果boolean将其设置为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);
        }

    });

在MainActivity中

    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 Class的列表

在MainActivity中实现接口

 @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();
}

答案 4 :(得分:0)

为两个字段月名制作一个pojo类,为下面的代码选择布尔值。

public class Month {
private String value;
public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

private boolean selectedFlag;


public boolean isSelectedFlag() {
    return selectedFlag;
}

public void setSelectedFlag(boolean selectedFlag) {
    this.selectedFlag = selectedFlag;
}

}

然后在make接口进入适配器后处理所选值的点击事件,如下所示..

   List<Month> mStringList = new ArrayList<>();// hear you can pass any pojo class object.
Context mContext;


    onItemClickListner onItemClickListner;

public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
    this.onItemClickListner = onItemClickListner;
}

public interface onItemClickListner {
    void onClick(Month str);//pass your object types.
}
    @Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    Month data = mStringList.get(position); // if you pass object of class then create that class object.
    if (data.isSelectedFlag()){
        holder.textView.setBackgroundColor(Color.RED);
    }
    else{
        holder.textView.setBackgroundColor(Color.WHITE);

    }
    // below code handle click event on recycler view item.
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onItemClickListner.onClick(data);
        }
    });
}

然后在将所有Month名称定义为Month类对象并将所选值false设置为false之后,将对象添加到列表中并绑定到适配器中。 在适配器绑定到recycleler视图后,然后调用下面的代码..

recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
        @Override
        public void onClick(Month str) {
            str.setSelectedFlag(true);
            recyclerViewAdpater.notifyDataSetChanged();
        }
    });