Issue
How to actually set the alpha/opacity for spanned text using SpannableStringBuilder in Android? I want to achieve this design in one TextView:
The main text Current location have full opacity/alpha (1.0) and the sub text Kungstan 43 have opacity of 84%.
I have set the SpannableStringBuilder as follows:
SpannableStringBuilder OriginText = new SpannableStringBuilder();
OriginText.Append(OriginMainText + ", ");
int SubTextIndex = OriginText.Length();
OriginText.Append(OriginSubText);
OriginText.SetSpan(<what need to set here??>, SubTextIndex, OriginText.Length(), 0)
What object should I put in <what need to set here??>? The closest approach is to set the foreground color but I prefer if it has way to set the alpha/opacity.
Solution
You can use the TextAppearanceSpan.
OriginText.setSpan(new TextAppearanceSpan(...), SubTextIndex, OriginText.Length(), 0);
The syntax is:
TextAppearanceSpan(String family,
int style,
int size,
ColorStateList color,
ColorStateList linkColor)
The important parameter for you here is the ColorStateList color, which is defined like this:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
android:color="@color/sample_focused" />
<item android:state_pressed="true"
android:state_enabled="false"
android:color="@color/sample_disabled_pressed" />
<item android:state_enabled="false"
android:color="@color/sample_disabled_not_pressed" />
<item android:color="@color/sample_default" />
</selector>
Starting with API 23, items may optionally define an android:alpha attribute to modify the base color's opacity, which is what you want. For example, the following item has 84% opacity as you wanted:
<item android:state_enabled="false"
android:color="?android:attr/colorAccent"
android:alpha="0.84" />
To get the color definition from resource, you can use:
ContextCompat.getColor(context, R.color.your_color);
Answered By - Racil Hilan

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.