如何在RecyclerView中突出显示所选项目

时间:2016-08-25 06:39:03

标签: android android-recyclerview recycler-adapter

我已经使用RecyclerView在我的图像编辑应用程序中显示缩略图。它的每个项目包含一个ImageView(缩略图)和一个textView。在我的应用程序中,我想突出显示当前选定的缩略图点击了。通过SO上的所有相关帖子,但无法找到更好的解决方案。

我的适配器类

    public class FiltersAdapter extends RecyclerView.Adapter<FiltersAdapter.ViewHolder> {

    private Context mContext;
    private List<Type> mDataSet;
    private Uri selectedPhoto;

    public enum Type {
        Original,
        Grayscale,
        Sepia,
        Contrast,
        Invert,
        Pixel,
        Sketch,
        Swirl,
        Brightness,
        Vignette
    }

    public FiltersAdapter(Context context, List<Type> dataSet, Uri selectedPhoto) {
        mContext = context;
        mDataSet = dataSet;
        this.selectedPhoto = selectedPhoto;
    }

    @Override
    public FiltersAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.list_item_layout, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(FiltersAdapter.ViewHolder holder, int position) {
        switch (mDataSet.get(position)) {
            case Original:
                holder.image.setImageResource(R.drawable.no_filter);
                break;
            case Grayscale:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new GrayscaleTransformation())
                        .into(holder.image);
                break;
            case Sepia:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new SepiaFilterTransformation(mContext))
                        .into(holder.image);
                break;
            case Contrast:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new ContrastFilterTransformation(mContext, 2.0f))
                        .into(holder.image);
                break;
            case Invert:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new InvertFilterTransformation(mContext))
                        .into(holder.image);
                break;
            case Pixel:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new PixelationFilterTransformation(mContext, 20))
                        .into(holder.image);
                break;
            case Sketch:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new SketchFilterTransformation(mContext))
                        .into(holder.image);
                break;
            case Swirl:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new SwirlFilterTransformation(mContext, 0.5f, 1.0f, new PointF(0.5f, 0.5f)))
                        .into(holder.image);
                break;
            case Brightness:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new BrightnessFilterTransformation(mContext, 0.5f))
                        .into(holder.image);
                break;
            case Vignette:
                Picasso.with(mContext)
                        .load(R.drawable.no_filter)
                        .transform(new VignetteFilterTransformation(mContext, new PointF(0.5f, 0.5f),
                                new float[]{0.0f, 0.0f, 0.0f}, 0f, 0.75f))
                        .into(holder.image);
                break;
            default:
                holder.image.setImageResource(R.drawable.no_filter);
                break;

        }
        holder.title.setText(mDataSet.get(position).name());
    }

    @Override
    public void onViewAttachedToWindow(ViewHolder holder) {
        super.onViewAttachedToWindow(holder);

    }

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

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        public ImageView image;
        public TextView title;

        ViewHolder(View itemView) {
            super(itemView);
            image = (ImageView) itemView.findViewById(R.id.thumbnailImage);
            title = (TextView) itemView.findViewById(R.id.title);
        }


    }
}

片段代码

horizontalFilters = (RecyclerView) mView.findViewById(R.id.rvHorizontal);
    LinearLayoutManager horizontalLayoutManagaer
            = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
    horizontalFilters.setLayoutManager(horizontalLayoutManagaer);

    List<Type> dataSet = new ArrayList<>();
    dataSet.add(Type.Original);
    dataSet.add(Type.Grayscale);
    dataSet.add(Type.Sepia);
    dataSet.add(Type.Contrast);
    dataSet.add(Type.Invert);
    dataSet.add(Type.Pixel);
    dataSet.add(Type.Sketch);
    dataSet.add(Type.Swirl);
    dataSet.add(Type.Brightness);
    dataSet.add(Type.Vignette);

    horizontalFilters.setAdapter(new FiltersAdapter(act, dataSet, selectedPhotoUri));

    horizontalFilters.addOnItemTouchListener(new RecyclerClick(act, horizontalFilters, new RecyclerClickListener() {
        @Override
        public void onClick(View view, int position) {
            switch (position){
                case 0:
                    photo.setImageDrawable(drawable);
                    break;
                case 1:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new GrayscaleTransformation())
                            .into(photo);
                    break;
                case 2:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new SepiaFilterTransformation(act))
                            .into(photo);
                    break;
                case 3:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new ContrastFilterTransformation(act, 2.0f))
                            .into(photo);
                    break;
                case 4:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new InvertFilterTransformation(act))
                            .into(photo);
                    break;
                case 5:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new PixelationFilterTransformation(act, 20))
                            .into(photo);
                    break;
                case 6:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new SketchFilterTransformation(act))
                            .into(photo);
                    break;
                case 7:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new SwirlFilterTransformation(act, 0.5f, 1.0f, new PointF(0.5f, 0.5f)))
                            .into(photo);
                    break;
                case 8:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new BrightnessFilterTransformation(act, 0.5f))
                            .into(photo);
                    break;
                case 9:
                    Picasso.with(act)
                            .load(selectedPhotoUri)
                            .transform(new VignetteFilterTransformation(act, new PointF(0.5f, 0.5f),
                                    new float[]{0.0f, 0.0f, 0.0f}, 0f, 0.75f))
                            .into(photo);
                    break;
                default:
                    photo.setImageDrawable(drawable);
                    break;
            }
        }

        @Override
        public void onLongClick(View view, int position) {

        }
    }));
}

9 个答案:

答案 0 :(得分:45)

只需在bindView

中添加以下内容即可
holder.itemView.setBackgroundColor(Color.parseColor("#000000"));

会为你效劳。

如果您想要突出显示所选项目,请执行以下操作

将其设为全球

int selectedPosition=-1;

在onBindViewHolder中 -

public void onBindViewHolder(FiltersAdapter.ViewHolder holder, int position) {
if(selectedPosition==position)
  holder.itemView.setBackgroundColor(Color.parseColor("#000000"));
else
  holder.itemView.setBackgroundColor(Color.parseColor("#ffffff"));

holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedPosition=position;
                notifyDataSetChanged();

            }
        });
}

答案 1 :(得分:5)

使用背景选择器并在布局xml中的 android:background 属性中为recyclelerview项设置

<强> background_selector.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/background_selector"
    android:orientation="vertical"
    android:paddingBottom="8dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp">

recyclerview_item.xml (在android:background属性中设置background_selector)

{{1}}

然后在您获得点击事件的地方,您可以使用查看功能

将其设置为已选中

<强> view.setSelected(真)

当您想要通过存储所选项目的位置取消选择/选择项目时,您必须实现逻辑

答案 2 :(得分:1)

可能只是使用:

android:background="?attr/selectableItemBackground"

对于项目xml中的根元素?

答案 3 :(得分:1)

创建模型日历模型名称

class CalenderModel {
var date: String
var isselected: Boolean
constructor(date: String, isselected: Boolean) {
    this.date = date
    this.isselected = isselected
}
 }

创建一个 Adapter CalenderAdapter 名称

class CalenderAdapter(
internal var activity: Activity,
internal var calenderModelList: ArrayList<CalenderModel>
) : RecyclerView.Adapter<CalenderAdapter.MyViewHolder>() {
var selected_defoult = 0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
    val itemView: View
    itemView =
        LayoutInflater.from(parent.context).inflate(R.layout.item_calenderdate, 
parent, false)
    return MyViewHolder(itemView)
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    val list = calenderModelList.get(position)
    holder.date_tv.text = Common.formateDate_calender_date(list.date)
    holder.day_tv.text = Common.formateDate_calender_day(list.date)
    if (position <= 3) {
        if (list.isselected) {
            holder.mLinearLayout.setBackgroundDrawable(
                ContextCompat.getDrawable(
                    activity,
                    R.drawable.selected_calender_background_green
                )
            )
        } else {
            holder.mLinearLayout.setBackgroundDrawable(
                ContextCompat.getDrawable(
                    activity,
                    R.drawable.selected_calender_background_gray
                )
            )
        }
    } else {
        holder.mLinearLayout.setBackgroundDrawable(
            ContextCompat.getDrawable(
                activity,
                R.drawable.selected_calender_background_gray_light
            )
        )
    }

    holder.itemView.setOnClickListener {
        if (position <= 3) {
            calenderModelList.get(selected_defoult).isselected = false
            calenderModelList.get(position).isselected = true
            selected_defoult = position
            notifyDataSetChanged()
        }
    }

   }

 override fun getItemCount(): Int {
    return calenderModelList.size
 }

override fun getItemId(position: Int): Long {
    return position.toLong()
}

override fun getItemViewType(position: Int): Int {
    return position
}


inner class MyViewHolder
internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {

    val day_tv: TextView
    val date_tv: TextView
    val mLinearLayout: LinearLayout

    init {
        mLinearLayout = itemView.findViewById(R.id.mLinearLayout)
        day_tv = itemView.findViewById(R.id.day_tv)
        date_tv = itemView.findViewById(R.id.date_tv)

    }
 }


 }

enter image description here

答案 4 :(得分:0)

首先将您的枚举更新为类,以获取标志

public class Type {
    public int type; // 0-Original,1-Grayscale,2-Sepia.... same as enum
    public int selected;
}

现在在适配器

@Override
public void onBindViewHolder(FiltersAdapter.ViewHolder holder, int position) {
    int typeOfItem = mDataSet.get(position).type
    switch (mDataSet.get(position)) {
        case 0:
            holder.image.setImageResource(R.drawable.no_filter);
            break;
        case 1:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new GrayscaleTransformation())
                    .into(holder.image);
            break;
        case 2:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new SepiaFilterTransformation(mContext))
                    .into(holder.image);
            break;
        case 3:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new ContrastFilterTransformation(mContext, 2.0f))
                    .into(holder.image);
            break;
        case 4:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new InvertFilterTransformation(mContext))
                    .into(holder.image);
            break;
        case 5:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new PixelationFilterTransformation(mContext, 20))
                    .into(holder.image);
            break;
        case 6:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new SketchFilterTransformation(mContext))
                    .into(holder.image);
            break;
        case 7:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new SwirlFilterTransformation(mContext, 0.5f, 1.0f, new PointF(0.5f, 0.5f)))
                    .into(holder.image);
            break;
        case 8:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new BrightnessFilterTransformation(mContext, 0.5f))
                    .into(holder.image);
            break;
        case 9:
            Picasso.with(mContext)
                    .load(R.drawable.no_filter)
                    .transform(new VignetteFilterTransformation(mContext, new PointF(0.5f, 0.5f),
                            new float[]{0.0f, 0.0f, 0.0f}, 0f, 0.75f))
                    .into(holder.image);
            break;
        default:
            holder.image.setImageResource(R.drawable.no_filter);
            break;
    }
    holder.title.setText(mDataSet.get(position).name());
    if(mDataSet.get(position).selected == 0){
        holder.title.setTypeface(null, Typeface.BOLD);
    } else {
        holder.title.setTypeface(null,Typeface.NORMAL);
    }
}

不是每次点击或选择更新您的列表然后调用适配器的notifydatasetChanged()

答案 5 :(得分:0)

在Kotlin中,您可以简单地完成某些人已经提到的Java。您将此代码放在适配器类中。

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    if (position < numItems) {
        // Bind your view here
        holder.itemView.setOnClickListener {
            it.setBackgroundResource(R.color.lightBlue)
        }
    }
}

答案 6 :(得分:0)

所以我们在回收站视图中有一个类ViewHolder和一个方法OnBindViewHolder()可以吗? 现在,当您在“回收者”视图中单击某个项目时,就会从视图持有者类为该视图调用OnClickMethod。现在创建一个整数变量int previousClickedItemPosition = -1 ;

现在,在viewHolderClass的onClickListener方法中,将这一行, previousClickedItemPosition = getAdapterPosition(); 从这里,我们可以找到最近单击的项目的位置。

现在,在OnBindViewHolder()中将项目背景的颜色设置为蓝色,

holder.fileNameTextView.setTextColor(Color.BLUE)

现在在OnclickListener中放置这些行

holder.fileNameTextView.setTextColor(Color.YELLOW);

if(previousClickedItemPosition != getAdapterPosition()) {
notifyDataSetchanged(previousClickedItemPosition );
}

提示是,当我们调用notifyDataSetchanged时,将调用onBindViewHolder。

因此,当您启动回收站视图时,所有颜色均为蓝色。 当您单击某个项目时,颜色将为黄色。 当您单击下一个项目时,上一个项目的颜色将为蓝色,而对于当前项目,该颜色将为黄色。

答案 7 :(得分:0)

android:background="?attr/selectableItemBackground"
android:clickable="true"
android:focusableInTouchMode="true"

答案 8 :(得分:0)

如果您不想要使用notifyDataSetChanged
由kotlin实施

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    adapterOrders = OrdersSendAdapter(this, listOrders)
    recyclerOrders = view.findViewById<RecyclerView>(R.id.recycler_orders)
    recyclerOrders.layoutManager = LinearLayoutManager(activity)
    recyclerOrders.setHasFixedSize(true)
    recyclerOrders.addItemDecoration(DividerItemDecoration(activity, DividerItemDecoration.VERTICAL))
    recyclerOrders.adapter = adapterOrders
  }

/* This method will be call when item of adapter has an event */
fun getListDetail(position: Int, idOrders: String) {
    for (index in 0 until recyclerOrders.childCount) {
         recyclerOrders[index].setBackgroundColor(Color.parseColor("#ffffff"))
    }
    recyclerOrders[position].setBackgroundColor(ContextCompat.getColor(context!!, R.color.color_select))
}