为了使其更简单,您有一个包含一组属性的自定义视图。要提供值,从底部(视图)到顶部(应用程序)有三种不同的方式
- 从属性或以编程方式为视图提供值
- 创建不同的样式并使用
style="@style/MyStyle"
- 创建一个属性并将其分配给
defStyleAttr
自定义视图的构造函数的参数。并在您的主题中为该属性分配样式,瞧!
对于前两个,它是直截了当的。让我们专注于最后一种方法。有四个步骤可以实现
步骤1
创建一个属性(一般在res/values/attrs.xml
文件中
<resources>
<attr name="myCustomViewAttr" format="reference" />
<!-- Below are your set of attributes in declare styleable -->
<declare-styleable name="TextInputLayout">
<attr format="reference" name="hintTextAppearance"/>
<attr name="android:hint"/>
<attr format="boolean" name="errorEnabled"/>
<attr format="reference" name="errorTextAppearance"/>
<attr format="boolean" name="counterEnabled"/>
<attr format="integer" name="counterMaxLength"/>
<attr format="reference" name="counterTextAppearance"/>
<attr format="reference" name="counterOverflowTextAppearance"/>
<attr name="android:textColorHint"/>
<attr format="boolean" name="hintAnimationEnabled"/>
</declare-styleable>
</resources>
第2步
在自定义视图中使用这个新创建的属性。
假设您的自定义视图的类名是MyCustomView
. 你的类的构造函数看起来像这样
class MyCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.myCustomViewAttr
) : TextInputLayout(context, attrs, defStyleAttr)
如果没有为布局中的属性提供任何内容,这将强制MyCustomView
使用属性。myCustomViewAttr
第 3 步
创建一个样式,这是最简单且被大多数人使用的样式
<style name="Widget.MyApp.MyCustomView" parent="">
<!-- Assuming you have already defined TextAppearance.MyApp.ErrorText as you required -->
<item name="errorTextAppearance">@style/TextAppearance.MyApp.ErrorText</item>
</style>
如果您想为您的 分配一些其他属性errorTextAppearance
,那么
<style name="Widget.MyApp.MyCustomView" parent="">
<!-- Assuming you have already defined TextAppearance.MyApp.ErrorText as you required -->
<item name="errorTextAppearance">?attr/myAnotherDefinedAttribute</item>
</style>
第4步
最后一步,将样式分配给属性
<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
<item name="myCustomViewAttr">@style/Widget.MyApp.MyCustomView</style>
</style>
如果您的文本外观来自其他属性,那么您可以直接分配该属性
<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
<item name="myCustomViewAttr">?attr/textAppearanceForError</style>
</style>