Android Values文件作用及使用方法

本文详细介绍了Android开发中res/values文件夹下四种XML文件的作用及使用方法,包括colors.xml用于保存颜色资源,dimens.xml用于尺寸控制,strings.xml用于管理字符串资源,以及styles.xml用于定义应用主题样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Android valuses

位于app/res/values文件是用来存放安卓资源的资源的文件其中包括四个个XML文件:

这里写图片描述

1. colors.xml
保存颜色资源

例如:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

2. dimens.xml 尺寸控制

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>

dimens.xml(w820dp)
先解释一下w820dp的意思,(可能是为电视设置的)
1. values-w820dp表明这个目录下的资源所要求屏幕的最小宽度是820dp。
2. Samsung G920V的屏幕配置参数:1440x2560像素,屏幕尺寸5.1寸,dpi=576.所以,Samsung G920V的最小屏幕宽度为:400dp (1440 * 160 / 576),因此不满足w820dp的要求。

<resources>
    <!-- Example customization of dimensions originally defined in res/values/dimens.xml
         (such as screen margins) for screens with more than 820dp of available width. This
         would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). 
     示例自定义维度最初定义在res /价值/ dimens.xml
    (如屏幕边缘)的屏幕宽度超过820 dp的可用。这
    包括7“10”设备景观(~ 960 dp ~ 960 dp分别)。-->
    <dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

3. string.xml

<resources>
    <string name="app_name">MyFirst</string>
</resources>

4. style.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

引用方式举例:
在代码中通过 R.string.app_name 可以获取app_name所对应的字符串(MyFirst)
在XML中通过 @string/app_name 可以获取app_name所对应的字符串(MyFirst)
(其他同理,相信聪明的你可以使用)


知其然,思其所以然
为什么要这么复杂?
这么复杂有卵用?

首先,这样做不复杂,反而更加方便。倘若一个程序中好多地方用到了一个String,要是没用这种全局常量的方式,需要一个一个地方改,反之则只需改一次,是不是方便了很多,虽然有的IDE有这个一改全改的功能,但是这是一种组件的开发思想。使用这种全局常量的方式也便于日后扩展复用等。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鼠晓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值