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有这个一改全改的功能,但是这是一种组件的开发思想。使用这种全局常量的方式也便于日后扩展复用等。