'Resource String Color not working programmatically in Android
string.xml Here is my string
<string name="bullet_text"><font color="#38d98a">●</font>\t\tCucumber Detox Water (1 glass)\n<font color="#38d98a">●</font>\t\tSkimmed Milk (1 glass)\n<font color="#38d98a">●</font>\t\tPeas Poha (1.5 katori)</string>
When this string is used in xml it works perfectly but when using this string programmatically then it does not works
xml code
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/bullet_text"
android:textSize="20sp"
android:layout_margin="10dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
Working Perfectly
Kotlin Code
val textView:TextView = findViewById(R.id.textView)
textView.text = getString(R.string.bullet_text)
Not Working Perfectly
Solution 1:[1]
Now It Works Answer is here thanks @ADM and @Rasheed for commenting help
strings.xml
<string name="bullet_text"><![CDATA[<font color="#38d98a">?</font>\t\tCucumber Detox Water (1 glass)<br/><font color="#38d98a">?</font>\t\tSkimmed Milk (1 glass)<br/><font color="#38d98a">?</font>\t\tPeas Poha (1.5 katori)]]></string>
Kotlin code
val textView: TextView = findViewById(R.id.textView)
textView.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(getString(R.string.hello_worldRed), Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(getString(R.string.hello_worldRed))
}
Output
Solution 2:[2]
you can use SpannableString to set bullet before your string :
val string = SpannableString("Text with\nBullet point")
string.setSpan(
BulletSpan(40, Color.GREEN, 20),
10,
22,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
binding.textView.text = string
here is the result
Also see this->BulletSpan
UPDATE
if (Build.VERSION.SDK_INT >= 28) {
val string = SpannableString("Text with\nBullet point")
string.setSpan(
BulletSpan(40, Color.GREEN, 20),
10,
22,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
)
binding.textView.text = string
}else {
// your own code
}
Solution 3:[3]
You can use custom style instead of string
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>
<item name="fontFamily">your font</item>
<item name="android:textColor">#38d98a</item>/>
</style>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yaqoob Bhatti |
Solution 2 | |
Solution 3 | Rasheed |