Android 在视图(而不是xml)中定义样式和自定义属性
我想实现视图的自定义样式。让我们以button为例。对于我正在使用的样式,一些通用值将在整个应用程序中共享,如下所示:Android 在视图(而不是xml)中定义样式和自定义属性,android,material-design,material-components-android,Android,Material Design,Material Components Android,我想实现视图的自定义样式。让我们以button为例。对于我正在使用的样式,一些通用值将在整个应用程序中共享,如下所示: <style name="Widget.Demo.Button.Primary" parent="@style/Widget.MaterialComponents.Button"> <item name="fontFamily">@font/roboto</item>
<style name="Widget.Demo.Button.Primary" parent="@style/Widget.MaterialComponents.Button">
<item name="fontFamily">@font/roboto</item>
<item name="android:fontFamily">@font/roboto</item>
<item name="android:minHeight">64dp</item>
<item name="android:theme">@style/ThemeOverlay.Demo.GrayPrimary</item>
</style>
<style name="ThemeOverlay.Demo.GrayPrimary" parent="">
<item name="colorPrimary">@color/gray</item>
</style>
我不想为我创建的每个按钮或视图定义xml样式。那么,有没有一种方法可以在CustomButton
类中定义自定义属性呢?如果是的话,你能给我一些推荐信吗
提前感谢。是的,您可以在构造函数中使用默认样式属性 定义新属性:
<com.android.CustomButton
android:id="@+id/btn_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/first"
app:abc="primary"
style="@style/Widget.Demo.Button.Primary"/>
attrs.xml:
<declare-styleable name="CustomButtonAttr" >
<attr name="abc" format="enum" >
<enum name="primary" value="1"/>
<enum name="secondary" value="2"/>
</declare-styleable>
然后使用适当的视图构造函数:
private val defStyleAttr=R.attr.customButtonStyle
类CustomButton(上下文:上下文,属性集):MaterialButton(
ThemeEnforce.CreateMetedContext(上下文,属性集,defStyleAttr,0),
属性集,
defstylettr
) {
初始化{
val typedArray=context.actainStyledAttributes(
属性,
R.styleable.CustomButton,
defstylettr,
0
)
...
}
在主题中,将customButtonStyle
指向默认情况下要使用的样式资源:
@style/Widget.Demo.Button.Primary
请注意,在该样式资源中,
android:theme
应更改为materialThemeOverlay
,因为从默认样式读取时不会应用它。因为您已经用ThemeEnforcement
函数包装了上下文(较新版本的材质设计组件将其更改为MaterialThemeOverlay
),此自定义视图支持materialThemeOverlay
此功能如我所愿,但是否有任何方法可以将自定义属性合并到样式中,而不是在每个位置进行定义?是的,只需将其粘贴到样式中即可。编辑了答案。顺便说一句,由于它是自定义视图,您可以在init
函数中设置主模式tion?不,所有本机和MDC小部件也是这样工作的
class CustomButton : MaterialButton {
constructor(context: Context) : super(context)
constructor(context: Context, attributeSet: AttributeSet) : super(
ThemeEnforcement.createThemedContext(context, attributeSet, 0, 0),
attributeSet,
0
)
}