在layout中:
<TextView android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="A"
android:textSize="?normal_font_size"
/>
在attrs.xml中
<?xml version="1.0" encoding="utf-8"?> <resources> <attr name="normal_font_size" format="dimension" /> </resources>
在themes.xml中
<style name="MainTheme" parent="@android :style/Theme.Black.NoTitleBar"> <item name="normal_font_size">15px</item> </style>
问题:在代码中如何动态读取我在主题中定义的值?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在Android中,如果你想在代码中动态读取在主题(themes.xml)中定义的属性值,比如你提到的?normal_font_size
,你可以通过以下步骤来实现:
确保你的自定义属性已正确声明:首先,在attrs.xml
文件中,你需要定义这个自定义属性。如果normal_font_size
是一个字体大小,那么它可能已经被定义为如下:
<resources>
<attr name="normal_font_size" format="dimension"/>
</resources>
在主题中设置该属性值:接着,在themes.xml
中,你需要为应用的主题或者某个特定的样式设置这个属性的默认值。
<resources>
<!-- Base application theme -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="normal_font_size">16sp</item>
...
</style>
</resources>
在代码中获取属性值:要在Java或Kotlin代码中动态获取这个属性值,你可以使用TypedValue
和getTheme().resolveAttribute()
方法。下面是一个示例代码片段:
// Java 示例
TypedValue typedValue = new TypedValue();
if (getTheme().resolveAttribute(R.attr.normal_font_size, typedValue, true)) {
int fontSize = typedValue.data;
// 现在你可以使用 fontSize 变量了
}
// Kotlin 示例
val typedValue = TypedValue()
if (theme.resolveAttribute(R.attr.normal_font_size, typedValue, true)) {
val fontSize = typedValue.data
// 现在你可以使用 fontSize 变量了
}
这段代码会从当前活动的主题中查找normal_font_size
属性,并将其值存储在typedValue
中,然后你可以根据需要使用这个值。请注意,这只是一个基本示例,实际使用时你可能需要根据具体需求调整代码。