如何在RecyclerView中更新项目的特定TextView?

如何解决如何在RecyclerView中更新项目的特定TextView?

当用户单击其他项目时,我想更新RecyclerView中的上一个TextView项目:

例如,如果用户单击“ lemanju” TextView,它将字体颜色更改为橙​​色,而当用户单击“ Lightning” TextView时,lemanju的字体颜色应恢复为黑色,而Lighning的字体颜色必须变为橙色,如下所示。

lemanju being selected

Lightning being selected (How I expect it to work)

Lightning being selected (What is happening now -> not updating lemanju's font color back to black)

我在适配器类中尝试了以下代码以实现此结果:

// set previous item TextColor to black.
 holder.itemView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
 holder.adapter.notifyItemChanged(previousSamplePosition);

 // set actual item TextColor to orange.
 holder.itemView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));

不幸的是,当我单击Lightning时,我无法将lemanju的字体颜色改回黑色。

有人知道如何使用notifyItemChanged更改特定的TextView吗?还是有另一种方法可以实现?

我的适配器类中的onCreateViewHolder方法可以在下面看到:

/**
     * Sets the contents of an item at a given position in the RecyclerView.
     * Called by RecyclerView to display the data at a specificed position.
     *
     * @param holder         The view holder for that position in the RecyclerView.
     * @param samplePosition The position of the item in the RecyclerView.
     *                       <p>
     */
    @Override
    public void onBindViewHolder(@NonNull SampleViewHolder holder,int samplePosition) {

        if (sampleList  != null) {
            Sample currentSample = sampleListFiltered.getCurrentList().get(samplePosition);
            // Add the data to the view holder.
            holder.sampleView.setText(currentSample.getName());
            holder.bind(currentSample);

            if (sampleNameSearched != null) {

                String sampleName = Normalizer.normalize(sampleListFiltered.getCurrentList().get(samplePosition).getName(),Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]","").toLowerCase();
                Pattern sampleQuery = Pattern.compile(sampleNameSearched);
                Matcher sampleMatcher = sampleQuery.matcher(sampleName);
                SpannableStringBuilder spanString = new SpannableStringBuilder(sampleListFiltered.getCurrentList().get(samplePosition).getName());

                while (sampleMatcher.find()) {
                    spanString.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD),sampleMatcher.start(),sampleMatcher.end(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                }
                holder.sampleView.setText(spanString);
            } else {
                // This solved the problem
                holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
            }
        }

        Bundle sampleBundle = new Bundle();

        holder.sampleView.setOnClickListener(view -> {
            sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());
            SampleCollectorListNavigatorFragment.addScreenToStack(0);
            SampleCollectorListNavigatorFragment.setLastSurveyIdAccessed(sampleListFiltered.getCurrentList().get(samplePosition).getSurveyId());
            Navigation.findNavController(view).navigate(R.id.action_sampleCollectorListNavigator_to_sampleCollectorInspectSampleFragment,sampleBundle);
        });

        holder.sampleView.setOnLongClickListener(view -> {

            sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());

            if (sampleID == 0) {
                // Access the view of the previous screen
                ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
                holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
            } else if (sampleID == sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
                if (((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).getVisibility() == View.VISIBLE) {
                    ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.GONE);
                    holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
                } else {
                    ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
                    holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
                }
            } else if (sampleID != sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
                holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
                notifyItemChanged(previousSamplePosition);
                holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
                ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
            }

            sampleID = sampleListFiltered.getCurrentList().get(samplePosition).getId();
            previousSamplePosition = samplePosition;

            return true;
        });
    }
}

更新->如何解决此问题?

要解决代码中的问题,我必须在搜索过滤器中将字符串更新回黑色:

// This solved the problem         
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));

但是,如果您的结构与我的不同,或者您只想更新回收站中的上一个TextView项目,则可以使用以下部分代码:

holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
notifyItemChanged(previousSamplePosition);

notifyItemChanged(previousSamplePosition)可以解决问题。

解决方法

这是一个基本示例,下面我也添加了您的代码

您的适配器

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
    
    
    private String[] mDataset;
    List<TextView> textViews = new ArrayList<>();
    
    
    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item,and
    // you provide access to all the views for a data item in a view holder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView textView;
        public MyViewHolder(TextView v) {
            super(v);
            textView = v.findViewById(R.id.textView);
        }
    }
    
    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.my_text_view,parent,false);
       
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder,int position) {
        holder.textView.setText(mDataset[position]);
        views.add(holder.textView);

    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
    
    public List<TextView> getTextViews(){
        return textViews;
    }
}

您的活动

public class MainActivity extends AppCompatActivity {
    
    private Button changeColorButton;
    private RecyclerView recyclerView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        changeColorButton = findViewById(R.id.button);
        recyclerView = findViewById(R.id.recyclerView);
        
        MyAdapter adapter = new MyAdapter(new String[]{"Hello","world"});
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        changeColorButton.setOnClickListener(new OnClickListener() {
 
            @Override
            public void onClick(View view) {
                int length = adapter.getTextViews().size();
                List<TextView> textViews = adapter.textViews;
                
                for(int i=0; i<length; i++){
                    textViews.get(i).setTextColor(Color.parseColor("#bdbdbd"));
                }
            }
 
        });
    }
}

现在输入您的代码

public static class SampleViewHolder extends RecyclerView.ViewHolder {

        private final TextView sampleView;

        /**
         * Creates a new custom view holder to hold the view to display in the RecyclerView.
         *
         * @param sampleListView The view in which to display the data.
         * @param adapter        The adapter that manages the the data and views for the RecyclerView.
         */
        public SampleViewHolder(View sampleListView) {
            super(sampleListView);
            sampleView = sampleListView.findViewById(R.id.data_name);
        }
    }

    /**
     * Inflates an item view and returns a new view holder that contains it.
     * Called when the RecyclerView needs a new view holder to represent an item.
     *
     * @param parent   The view group that holds the item views.
     * @param viewType Used to distinguish views,if more than one type of item view is used.
     * @return a view holder.
     */
    @NonNull
    @Override
    public SampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
        // Inflate an item view.
        View sampleListView = inflater.inflate(R.layout.fragment_sample_collector_list_sample,false);
        return new SampleViewHolder(sampleListView);
    }

    /**
     * Sets the contents of an item at a given position in the RecyclerView.
     * Called by RecyclerView to display the data at a specificed position.
     *
     * @param holder         The view holder for that position in the RecyclerView.
     * @param samplePosition The position of the item in the RecyclerView.
     *                       <p>
     *                       TODO: Most important method used
     */
    @Override
    public void onBindViewHolder(@NonNull SampleViewHolder holder,int samplePosition) {

        if (sampleList != null) {
            // Retrieve the data for that position.
            //Sample currentSample = sampleListFiltered.get(samplePosition);
            Sample currentSample = sampleListFiltered.getCurrentList().get(samplePosition);
            // Add the data to the view holder.
            holder.sampleView.setText(currentSample.getName());
            holder.bind(currentSample);
            list.add(holder.sampleView);

            if (sampleNameSearched != null) {

                String sampleName = Normalizer.normalize(sampleListFiltered.getCurrentList().get(samplePosition).getName(),Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]","").toLowerCase();
                Pattern sampleQuery = Pattern.compile(sampleNameSearched);
                Matcher sampleMatcher = sampleQuery.matcher(sampleName);
                SpannableStringBuilder spanString = new SpannableStringBuilder(sampleListFiltered.getCurrentList().get(samplePosition).getName());

                while (sampleMatcher.find()) {
                    spanString.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD),sampleMatcher.start(),sampleMatcher.end(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                }
                holder.sampleView.setText(spanString);
            }
        }

        Bundle sampleBundle = new Bundle();
        holder.sampleView.setOnClickListener(view -> {
            sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());
            SampleCollectorListNavigatorFragment.addPreviousScreen(0);
            SampleCollectorListNavigatorFragment.setLastSurveyIdAccessed(sampleListFiltered.getCurrentList().get(samplePosition).getSurveyId());
            Navigation.findNavController(view).navigate(R.id.action_sampleCollectorListNavigator_to_sampleCollectorInspectSampleFragment,sampleBundle);
        });

        holder.sampleView.setOnLongClickListener(view -> {

            sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());

            // TODO: if the same button is clicked close the buttonPanel,else keep it open.
            if (sampleID == 0) {
                // Access the view of the previous screen
                ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
                holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
            } else if (sampleID == sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
                if (((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).getVisibility() == View.VISIBLE) {
                    ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.GONE);
                    holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
                } else {
                    ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
                    holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
                }
            } else if (sampleID != sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
                Toast.makeText(inflater.getContext(),"list size() " + list.size(),Toast.LENGTH_SHORT).show();
                // I CANNOT CHANGE THE COLOR OF THE PREVIOUS SAMPLE RIGHT HERE.
                List<RecyclerView.ViewHolder> vh = getItem();
                changeColor(vh,previousSamplePosition);
                holder.adapter.notifyItemChanged(previousSamplePosition);
                holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
                ((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
            }

            sampleID = sampleListFiltered.getCurrentList().get(samplePosition).getId();
            previousSamplePosition = samplePosition;

            return true;
        });
    }

    public List<RecyclerView.ViewHolder> getItem(){
        return list;
    }

    public void changeColor(List<RecyclerView.ViewHolder> vh,int previousSamplePosition) {
        for (int i = 0; i < list.size(); i++) {
            if(i == previousSamplePosition) {
                // Does not change the previous TextView.
                Toast.makeText(inflater.getContext(),"i -> " + i + " previousSamplePos -> " + previousSamplePosition,Toast.LENGTH_SHORT).show();
                // How can I use the vh here?
                //vh.get(i).setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
                //holder.adapter.notifyItemChanged(i);
            }
        }
    }
}

让我知道它是否有效

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-