Android Studio(Kotlin)中如何自定义TextView的TextAppearance
嘿,刚接触Android Studio和Kotlin的话,能想到用TextAppearance来统一样式真的超棒!这绝对是减少重复操作、保持UI一致性的好办法,我来一步步带你实现:
首先打开res/values/styles.xml(如果你的项目里没有这个文件,直接新建一个就行),添加一个继承自系统基础TextAppearance的自定义样式,把你需要的字体、字号、颜色都整合进去:
<style name="CustomTextViewStyle" parent="TextAppearance.AppCompat"> <!-- 字号用sp单位,适配不同屏幕,推荐必用 --> <item name="android:textSize">16sp</item> <!-- 文本颜色,支持十六进制色值或者@color资源引用 --> <item name="android:textColor">#FF4081</item> <!-- 自定义字体:先把字体文件(比如my_custom_font.ttf)放到res/font目录下,AS会自动生成引用 --> <item name="android:fontFamily">@font/my_custom_font</item> <!-- 还可以按需添加其他属性,比如字重、斜体 --> <item name="android:textStyle">bold</item> </style>
👉 这里用TextAppearance.AppCompat作为父样式,是为了兼容更多低版本的Android设备,如果你用的是Material Components主题,也可以继承TextAppearance.MaterialComponents.Body1这类更贴合设计规范的父样式。
接下来不管是activity_main.xml还是其他Activity的布局文件,只要给TextView设置android:textAppearance属性,引用你刚才定义的样式就行:
<TextView android:id="@+id/myTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:textAppearance="@style/CustomTextViewStyle" />
这样就不用每次都重复写textSize、textColor这些属性了,一行代码搞定所有样式!
如果想让整个App里的所有TextView默认都用这个样式,不用逐个布局设置,可以修改App的主题(在res/values/themes.xml或者styles.xml里的App主题),添加这两个属性:
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- 保留你原有的主题属性... --> <!-- 适配原生Android控件 --> <item name="android:textAppearance">@style/CustomTextViewStyle</item> <!-- 适配AppCompat/Material Components控件 --> <item name="textAppearance">@style/CustomTextViewStyle</item> </style>
这样所有没单独设置textAppearance的TextView都会自动套用你的自定义样式,省心又统一!
如果后续需要调整样式,只要修改styles.xml里的CustomTextViewStyle,所有引用它的TextView都会同步更新,再也不用逐个布局改啦~
内容的提问来源于stack exchange,提问作者marco

