【发布时间】:2020-03-12 19:38:22
【问题描述】:
我搜索了很多答案,但没有找到任何可行的解决方案。我想知道是否有可能以编程方式设置 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()
}
}
}
【问题讨论】:
-
到目前为止,您是否尝试过任何 Kotlin 代码?这与数据绑定有什么关系?我看到的唯一选择是创建一个自定义 LinearLayout → CustomLayout 并将各自的样式属性放在构造函数中。
-
@nulldroid 抱歉,我错过了添加自定义类
标签: android kotlin styles themes android-custom-view