无法通过自定义TextView android设置颜色

问题描述

您好
我需要实现一个自定义文本视图,以在我的应用程序的所有模块中使用。
通过自定义textview设置颜色时遇到了问题。
颜色不是通过自定义TextView设置的。
请找到我的实现并帮助我解决此问题

attrs.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <declare-styleable name="CustomFontTextView">
            <attr name="textColor"></attr>
        </declare-styleable>
         <attr name="textColor" format="enum">
        <enum name="Regular_Color" value="1"/>
      
    </attr>
</resources>

strings.xml:

<resources>
    <string name="app_name">TestApp</string>
    <string name="Regular_Color">colornormal</string>
</resources>

colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#6200EE</color>
    <color name="colorPrimaryDark">#3700B3</color>
    <color name="colorAccent">#03DAC5</color>
    <color name = "colornormal">#00FF00</color>
</resources>

CustomTextView:

    @RequiresApi(Build.VERSION_CODES.M)
    class CustomFontTextView   @JvmOverloads constructor(
        context: Context,attrs: AttributeSet? = null,defStyle: Int = 0,defStyleRes: Int = 0
    ) : AppCompatTextView(context,attrs,defStyle) {
        var customFont: String? = null
    
        init {
                attrs?.let {
val a = context.obtainStyledAttributes(
            attrs,R.styleable.CustomFontTextView
        )
                            setColor(a,context,attrs);
                 }
        }

 @SuppressLint("ResourceType")
    @RequiresApi(Build.VERSION_CODES.M)
    private fun setColor(typedArray: TypedArray,context: Context,attrs: AttributeSet){

        val cf = typedArray.getInteger(R.styleable.CustomFontTextView_textColor,0)
        var textViewColor = 0
        textViewColor = when(cf){
            1 -> R.color.colornormal
            else->R.string.Regular_Color
        }
     
        this.setTextColor(textViewColor)
        invalidate()
        requestLayout()
     

    }
}

运行该应用程序时,实际上未设置颜色,应该设置为绿色。

我的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.android.dynamicfeaturemodulesample.UI.CustomFontTextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="57dp"
        android:text="TextView"
        app:textColor="Regular_Color"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent />
</androidx.constraintlayout.widget.ConstraintLayout>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)