gpt4 book ai didi

Android Spannable 无法在回收器 View 适配器中工作

转载 作者:行者123 更新时间:2023-12-02 10:12:32 26 4
gpt4 key购买 nike

我有一个回收器 View ,想要更改 TextView 文本某些部分的颜色。

这是我的代码:

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);

}
}
}

它不会改变颜色或文本大小。我做错了什么??

最佳答案

嗨,我已经实现了同样的事情并且它对我有用。您必须创建一个扩展 ClickableSpan 的类,如下所示:

    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);
}
}

然后在 onBindViewHolder() 方法中,您必须编写如下代码

     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());

希望这能解决您的问题

关于Android Spannable 无法在回收器 View 适配器中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42667343/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com