Set view style programmatically Kotlin

Viewed 5771

I searched for many answers but didn't find any working solution. I wonder if there is some possibility to set Edittext style programmatically. In my situation, I have one layout which is included and used in two different places and beside the place where it is included need to use a different style.

<style name="TestStyle1" parent="Widget.AppCompat.EditText">
    <item name="android:maxLength">1</item>
    <item name="android:singleLine">true</item>
</style>

<style name="TestStyle2" parent="CodeTextStyle">
    <item name="android:alpha">0.5</item>
</style>

first_activity.xml

  <include
        layout="@layout/custom_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

second_activity.xml

  <include
        layout="@layout/custom_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

custom_layout.xml

  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <CustomEditText
        android:id="@+id/et"
        app:style_ref="@style/CustomTextStyle"
        style="@style/TestStyle1" <-- Here i need to change style beside of usage
        android:layout_height="wrap_content" />
</LinearLayout>

CustomEditText.kt

class CustomEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : AppCompatEditText(context, attrs) {

init {
    val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.CustomEditText, 0 , 0)
    try {

        val style2 = typedArray.getResourceId(R.styleable.CustomEditText_style_ref, 0)

        setTypeface(Typeface.DEFAULT, style2)
        invalidate()
    }
}

}

2 Answers

So the simplest way, if your min API level is 23 would be to get a reference of each CustomEditText instance after inflation of the respective activity layout, then just set

myCustomEditText.setTextAppearance(R.style.TestStyle1)

as explained in this answer (which is using the deprecated version of this)

Another option would be to apply the 2 styles to two respective app theme styles, which you can set to each activity in AndroidManifest.

Or you can go the more complicated path that I suggested in my comment: Create a custom LinearLayout class and pass the style in the constructor:

class CustomLayout(context: Context) : LinearLayout(context, null, R.style.TestStyle1)

You would just need to figure out a way to let the layout know which activity it is created. As far as I know, that style would then get passed on to each child view, your CustomEditText respectively.

Related