如何在RecyclerView中突出显示视图

时间:2018-07-12 04:52:31

标签: java android

当我在RecyclerView中选择一个项目时,我试图更改背景颜色,但是由于这是一项相当新的功能,因此没有任何快速简便的答案。选择器也不适合我。

列出项目xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list_item_bg"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

</android.support.constraint.ConstraintLayout>

Java代码

public class ScheduleTabAdapter extends RecyclerView.Adapter<ScheduleTabAdapter.ScheduleViewHolder> {

 public class ScheduleViewHolder extends RecyclerView.ViewHolder {

            @Bind(R.id.list_item_bg) ConstraintLayout mCL_BG;

            private Context mContext;

        //This is used for setting onClick methods for each item
        public ScheduleViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            mContext = itemView.getContext();
        }

   }

build.gradle

 annotationProcessor 'com.jakewharton:butterknife:7.0.1'
 implementation 'com.jakewharton:butterknife:7.0.1'

2 个答案:

答案 0 :(得分:0)

更新:遵循本指南

https://stackoverflow.com/a/49704439/6147989

旧答案

将此行代码添加到ScheduleViewHolder(View itemView)方法中。

   itemView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    if (event.getAction() == MotionEvent.ACTION_MOVE){
                        mCL_BG.setBackgroundColor(Color.GRAY);
                    } else {
                        mCL_BG.setBackgroundColor(Color.TRANSPARENT);
                    }
                    return false;
                }
            });

//interesting fact, this will not work unless you have a OnClickListener
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                }
            });

答案 1 :(得分:0)

class Program { public static void Main(string[] args) { var s = new StringBuilder(); s.Append("Id,Name\r\n"); s.Append("1,one\r\n"); s.Append("2,two\r\n"); using (var reader = new StringReader(s.ToString())) using (var csv = new CsvReader(reader)) { csv.Configuration.RegisterClassMap<TestMap<Test>>(); csv.GetRecords<Test>().ToList(); } } } public class Test : Test1 { public int Id { get; set; } public string Name { get; set; } } public Abstract class Test1 { public decimal Extra { get; set; } } public class Test2 : Test1 { //other propertys } public class TestMap<T> : CsvClassMap<T> where T : Test1 { public TestMap() { AutoMap(); Map(m => m.Extra).Ignore(); } } 添加到RecyclerView适配器所展开的布局的父元素中(您的Recycler项目布局)

使用此link进行详细说明