I want to set a spannable
string in my text view when a button is clicked, where the first word has white foreground color and striked out and the second word has red foreground color. This is my code:
My textview:
<TextView
android:id="@ id/charge_per_month"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16pt">
</TextView>
My java code:
TextView charge_month = findViewById(R.id.charge_per_month);
String exp_amount = "₹ 5600"; //should be white in color and striked out
String act_amount = "₹ 6708"; //should be red in color
String complete_string = exp_amount " " act_amount;
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Spannable str = new SpannableString (complete_string);
str.setSpan(new StrikethroughSpan(), 0, exp_amount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new ForegroundColorSpan(Color.WHITE),0, exp_amount.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new ForegroundColorSpan(Color.RED),exp_amount.length() 1,complete_string.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
charge_month.setText(str);
}
}
The spannable string just shows for a split second, when the button is clicked. How do I fix this?
CodePudding user response:
change this from:
str.setSpan(new ForegroundColorSpan(Color.RED),exp_amount.indexOf(exp_amount.charAt(0)),act_amount.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
to
str.setSpan(new ForegroundColorSpan(Color.RED),exp_amount.length() 1,complete_string.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
CodePudding user response:
Try This
TextView charge_month = findViewById(R.id.charge_per_month);
String exp_amount = "₹ 5600";
String act_amount = "₹ 6708";
String complete_string = exp_amount " " act_amount;
Spannable str = new SpannableString(complete_string);
str.setSpan(new StrikethroughSpan(), 0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new ForegroundColorSpan(Color.WHITE),0, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(new ForegroundColorSpan(Color.RED),6, str.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
charge_month.setText(str);
click this link to check out look like - https://imgur.com/hiBflU3