簡體   English   中英

資源字符串顏色在 Android 中無法以編程方式工作

[英]Resource String Color not working programmatically in Android

string.xml這是我的字符串

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

當在 xml 中使用此字符串時,它可以正常工作,但是當以編程方式使用此字符串時,它就不起作用

xml代碼

<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"
        />

完美工作

在此處輸入圖像描述

Kotlin 代碼

 val textView:TextView = findViewById(R.id.textView)
 textView.text = getString(R.string.bullet_text)

工作不完美

在此處輸入圖像描述

現在可以了 答案在這里感謝@ADM 和@Rasheed 提供評論幫助

字符串.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>

科特林代碼

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

輸出

在此處輸入圖像描述

您可以使用 SpannableString 在您的字符串之前設置項目符號:

val string = SpannableString("Text with\nBullet point")
        string.setSpan(
            BulletSpan(40, Color.GREEN, 20),
            10,
            22,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        binding.textView.text = string

這是結果

在此處輸入圖像描述

另請參閱此-> BulletSpan

更新

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM