Search code examples
androidandroid-recyclerviewspannablestringbuilder

Android Spannable not working in recycler view adapter


I have a recycler view and want to change color of some part of textview text.

Here's my code:

public class MyAdapter extends RecyclerView.Adapter<MyEarningsAdapter.ViewHolder> {
    public ArrayList<WageItemDataSet> wageItemList;
    private Context context;
    private Spannable spanText;
    private ForegroundColorSpan fcs;
    private RelativeSizeSpan rss;
    public MyAdapter(Context context) {
        wageItemList = new ArrayList<>();
        this.context = context;
        fcs = new ForegroundColorSpan(Color.BLACK);
        rss = new RelativeSizeSpan(0.8f);
    }
 @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_wage_list, parent, false));
    }
    @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            WageItemDataSet item = wageItemList.get(position);
            spanText = new SpannableString("Fare: "+item.totalFare);
            spanText.setSpan(fcs, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            spanText.setSpan(rss, 0, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.tvFareAmount.setText(spanText);

        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvFareAmount;
            public ViewHolder(View itemView) {
                super(itemView);
                tvFareAmount = (TextView) itemView.findViewById(R.id.tvFareAmount);

                tvFareAmount.setTypeface(openSansRegular);

            }
        }
}

It doesn't change color or the text size. What am I doing wrong??


Solution

  • Hi I have implemented the same thing and its working for me. You have to make one class that extend ClickableSpan like it as below:

        public class TextSpan extends ClickableSpan {
          @Override
          public void onClick(View widget) {
          TextView tv = (TextView) widget;
          Spanned s = (Spanned) tv.getText();
          //int start = s.getSpanStart(this);
          //int end = s.getSpanEnd(this);
        }
      }
    

    and then in your on onBindViewHolder() method you have to write this code as below

         SpannableStringBuilder builder = new SpannableStringBuilder();
         builder.append("yourstring");
         builder.setSpan(new TextSpan(), builder.length() -        
         comment.length(),builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
         holder.tvFareAmount.setText(content);
      holder.tvFareAmount.setMovementMethod(LinkMovementMethod.getInstance());
    

    I hope this will resolve your problem