开发者社区 问答 正文

android 读取 attr 资源:报错

在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> 
问题:在代码中如何动态读取我在主题中定义的值?

展开
收起
kun坤 2020-06-08 19:15:16 690 分享 版权
阿里云 AI 助理回答

在Android中,如果你想在代码中动态读取在主题(themes.xml)中定义的属性值,比如你提到的?normal_font_size,你可以通过以下步骤来实现:

  1. 确保你的自定义属性已正确声明:首先,在attrs.xml文件中,你需要定义这个自定义属性。如果normal_font_size是一个字体大小,那么它可能已经被定义为如下:

    <resources>
        <attr name="normal_font_size" format="dimension"/>
    </resources>
    
  2. 在主题中设置该属性值:接着,在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>
    
  3. 在代码中获取属性值:要在Java或Kotlin代码中动态获取这个属性值,你可以使用TypedValuegetTheme().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中,然后你可以根据需要使用这个值。请注意,这只是一个基本示例,实际使用时你可能需要根据具体需求调整代码。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答