以编程方式设置Kotlin的视图样式

问题描述 投票:0回答:1

我搜索了很多答案,但没有找到任何可行的解决方案。我想知道是否有可能以编程方式设置Edittext样式。在我的情况下,我有一个包含在两个不同位置并在其中使用的布局,并且在包含该位置的位置旁边需要使用不同的样式。

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

}

android kotlin styles themes android-custom-view
1个回答
0
投票

因此,最简单的方法是,如果您的最低API级别为23,则需要在各个活动布局膨胀后获取每个CustomEditText实例的引用,然后才进行设置

myCustomEditText.setTextAppearance(R.style.TestStyle1)

this answer中所述(正在使用此版本的不推荐使用的版本)

另一个选择是将这两种样式应用于两种各自的应用程序主题样式,您可以将其设置为AndroidManifest中的每个活动。

或者您可以走我在评论中建议的更复杂的路径:创建一个自定义LinearLayout类,然后在构造函数中传递样式:

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

您只需要找出一种方法使布局知道创建了哪个活动。据我所知,该样式将分别传递到每个子视图,即CustomEditText。

© www.soinside.com 2019 - 2024. All rights reserved.