BackgroundColorSpan在RecyclerView中不起作用

时间:2019-01-08 06:45:38

标签: android android-recyclerview

BackgroundColorSpanrecyclerView中不起作用。它可以与listView一起正常工作,但不能与recyclerView一起工作。知道为什么吗?或者我该如何克服这个问题。

@Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.no.setText(String.valueOf(position + 1));
        ExerciseRoutineService exerciseRoutineService = 
        exerciselist.get(position);
        String exerciseText = "i exercise by " + 
                                  exerciseRoutineService.getExerciseType()
                                  + " for about " + 
                                  exerciseRoutineService.getFrequency() + 
                                  " " + 
                                  exerciseRoutineService.getDuration() + " 
                                  minutes";
        holder.exercise.setText(exerciseText);
        int start;
        start=exerciseText.indexOf
        (exerciseRoutineService.getExerciseType());
        int end = start + 
        exerciseRoutineService.getExerciseType().length();
        StringBuilder captionBuilder = new StringBuilder();
        captionBuilder.append(exerciseText);
        SpannableStringBuilder commentBuilder = new 
        SpannableStringBuilder(captionBuilder);
        commentBuilder.setSpan(new BackgroundColorSpan(Color.GREEN), 
        start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        holder.exercise.setText(commentBuilder);
 }

1 个答案:

答案 0 :(得分:0)

更改跨度附加到的文本的背景颜色。 例如,要为文本设置绿色背景颜色,您将基于文本创建SpannableString并设置跨度。

SpannableString string = new SpannableString("Text with a background color span");
string.setSpan(new BackgroundColorSpan(color),12,28,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

或者请看这里 SpannableStringBuilder  和 Developer.android.com

相关问题