本文将继续介绍App Resources中的资源类型(Animation、Color State List、String、Style)。
如果需要了解Android中的资源规范,您可以访问我翻译的这篇官方文档:《Android官方文档之App Resources(上)》。
如需访问官方原文,您可以点击这个链接:《Resource Types》。
在下1篇文章中(Android官方文档之App Resources(下)),将介绍App Resources中其余的资源类型(Layout、Menu、Drawable)。
资源类型(Resource Types)
本节将介绍Android中各种资源的类型、格式、语法、和援用方式。
动画资源(Animation Resources)
配置预定义的动画(Define pre-determined animations)。
其中补间动画(Tween animations)应存储于res/anim/目录下,并通过R.anim援用;
帧动画(Frame animations)应存储于 res/drawable/目录下,并通过 R.drawable援用;
属性动画(Object animations)应存储于res/animator/目录下,并通过R.animator援用。
如需了解有关动画的介绍,您可以访问我翻译的文档:《Android官方文档之Animation》
属性动画(Property Animation)
文件目录:
res/animator/filename.xml
核心类:
ValueAnimator, ObjectAnimator, AnimatorSet。
援用方式:
In Java: R.animator.filename
In XML: @[package:]animator/filename
语法:
android:ordering=["together" | "sequentially"]>
android:propertyName="string"
android:duration="int"
android:valueFrom="float | int | color"
android:valueTo="float | int | color"
android:startOffset="int"
android:repeatCount="int"
android:repeatMode=["repeat" | "reverse"]
android:valueType=["intType" | "floatType"]/>
android:duration="int"
android:valueFrom="float | int | color"
android:valueTo="float | int | color"
android:startOffset="int"
android:repeatCount="int"
android:repeatMode=["repeat" | "reverse"]
android:valueType=["intType" | "floatType"]/>
...
根标签必须为, , 或 之1。
标签及其属性:
:可以包括其他动画标签,如, , 或 ,对应AnimatorSet类。
属性:
– android:ordering :指定动画播放顺序
Value
Description
sequentially
顺序履行
together(默许)
同时履行
:指定某个对象的属性在1定时间内履行的动画。对应ObjectAnimator类。
属性:
– android:propertyName :String类型,不可缺省。指定View对象的某个属性,如alpha、backgroundColor等。应调用loadAnimator()或setTarget()方法,将XML属性动画设置到包括了该属性的对象上。
– android:valueTo:float, int, 或 color类型,不可缺省。指定动画的结束值。其中color是1个6位的16进制数,如#333333。
– android:valueFrom:float, int, 或 color类型。指定动画的起始值。若未指定,则将通过属性的get()方法获得起始值。
– android:duration:int类型。动画履行的毫秒数,若未指定,则默许为300毫秒。
– android:startOffset:int类型。调用start()后延迟的毫秒数。
– android:repeatCount:int类型。动画的重复次数。设置为“⑴”表示无穷循环。设置为“0”表示不循环,即只履行1次。设置为“1”表示循环1次,即履行两次。
– android:repeatMode :int类型。当动画履行完后的行动。需配合android:repeatCount属性使用(不能为0,可以为正整数或⑴),reverse表示反向履行。repeat表示重复履行。
– android:valueType:intType或floatType(默许)。指定动画属性值的变化类型。若操作的属性是色彩,则不能指定该属性。
:在规定的时间内改变某个属性值。对应ValueAnimator类。
属性:
– android:valueTo:float, int, 或 color 类型,不可缺省。
– android:valueFrom:float, int, 或 color 类型,不可缺省。
– android:duration:int类型。缺省值为300毫秒。
– android:startOffset:int类型。
– android:repeatMode: int类型。
– android:valueType :intType、或floatType(默许)
举例:
android:duration="500"
android:valueTo="400"
android:valueType="intType"/>
android:duration="500"
android:valueTo="300"
android:valueType="intType"/>
android:duration="500"
android:valueTo="1f"/>
在Java代码中引入:
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext,
R.anim.property_animator);
set.setTarget(myObject);
set.start();
补间动画(View Animation/Tween animation)
文件目录:
res/anim/filename.xml
核心类:
Animation
援用方式:
In Java: R.anim.filename
In XML: @[package:]anim/filename
语法:
android:interpolator="@[package:]anim/interpolator_resource"
android:shareInterpolator=["true" | "false"] >
android:toAlpha="float" />
android:toXScale="float"
android:fromYScale="float"
android:toYScale="float"
android:pivotX="float"
android:pivotY="float" />
android:toXDelta="float"
android:fromYDelta="float"
android:toYDelta="float" />
android:toDegrees="float"
android:pivotX="float"
android:pivotY="float" />
...
根标签必须为, , , , 或之1。
标签及其属性:
:补间动画集合。对应AnimationSet类。
– android:interpolator:插值器资源。具体含义请参考《Android官方文档之Animation》中有关interpolator的介绍。
– android:shareInterpolator:Boolean类型。若设置为true,表示该标签中的所有直接子标签同享1个interpolator。
:透明度动画。淡入淡出效果(A fade-in or fade-out animation)。对应AlphaAnimation类。
– android:fromAlpha:Float类型。起始透明度。0.0表示完全透明,1.0表示完全不透明。
– android:toAlpha:Float类型。终止透明度。0.0表示完全透明,1.0表示完全不透明。
:缩放动画。对应ScaleAnimation类。
– android:fromXScale:Float类型。x方向的起始缩放比例,若为1.0,表示无缩放。
– android:toXScale:Float类型。x方向的终究缩放比例。
– android:fromYScale:Float类型。y方向的起始缩放比例,若为1.0,表示无缩放。
– android:toYScale:Float类型。y方向的终究缩放比例。
– android:pivotX:Float类型。x方向的缩放中心。
– android:pivotY:Float类型。y方向的缩放中心。
:平移动画。对应TranslateAnimation类。平移的值支持3种格式。1、值从⑴00到100,以%结束,表示相对自己本身平移。2、值从⑴00到100,以%p结束,表示相对父控件平移。3、没有后缀,只是1个值,表示平移的绝对数值。
– android:fromXDelta:Float 或百分比类型。x方向的起始平移位置。平移的距离为5dp(5);平移的距离为控件宽度的5%(5%);平移的距离为父控件宽度的5%(5%p)。
– android:toXDelta:Float 或百分比类型。x方向的终止平移位置。
– android:fromYDelta:Float 或百分比类型。y方向的起始平移位置。
– android:toYDelta:Float 或百分比类型。y方向的终止平移位置。
:旋转动画。对应RotateAnimation类。
– android:fromDegrees:Float类型。旋转起始角度。
– android:toDegrees:Float类型。旋转终止角度。
– android:pivotX :Float或百分比类型。x坐标旋转中心。
– android:pivotY:Float或百分比类型。y坐标旋转中心。
示例:
android:shareInterpolator="false">
android:fromXScale="1.0"
android:toXScale="1.4"
android:fromYScale="1.0"
android:toYScale="0.6"
android:pivotX="50%"
android:pivotY="50%"
android:fillAfter="false"
android:duration="700" />
android:startOffset="700">
android:toXScale="0.0"
android:fromYScale="0.6"
android:toYScale="0.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="400" />
android:toDegrees="⑷5"
android:toYScale="0.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="400" />
引入到代码中:
ImageView image = (ImageView) findViewById(R.id.image);
Animation hyperspaceJump = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
image.startAnimation(hyperspaceJump);
帧动画(Frame animation)
文件目录:
res/drawable/filename.xml
核心类:
AnimationDrawable
援用方式:
In Java: R.drawable.filename
In XML: @[package:]drawable.filename
语法:
android:oneshot=["true" | "false"] >
android:duration="integer" />
标签及属性:
:不可缺省,且必须作为根标签。
– android:oneshot :boolean类型。若为true表示重复履行。
:每帧动画。
– android:drawable:drawable资源。
– android:duration :这1帧的展现时间。
举例:
android:oneshot="false">
在Java中引入:
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
rocketAnimation.start();
色彩状态列表资源(Color State List Resource)
用于切换控件在不同状态时的不同色彩的资源文件。
文件位置:
res/color/filename.xml
核心类:
ColorStateList
援用方式:
In Java: R.color.filename
In XML: @[package:]color/filename
语法:
android:color="hex_color"
android:state_pressed=["true" | "false"]
android:state_focused=["true" | "false"]
android:state_selected=["true" | "false"]
android:state_checkable=["true" | "false"]
android:state_checked=["true" | "false"]
android:state_enabled=["true" | "false"]
android:state_window_focused=["true" | "false"] />
元素及属性:
:不可缺省。必须是根标签。并包括多个标签。
:定义某个状态下的色彩。
– android:color :不可缺省。16进制数。用于指定RGB值及可选的alpha通道:#RGB、#ARGB、#RRGGBB、#AARRGGBB
– android:state_pressed:boolean类型。表示控件是不是处于被点击( touched/clicked)状态。
– android:state_focused:boolean类型。表示控件是不是处于取得焦点状态。
– android:state_selected:boolean类型。表示控件是不是被选中。
– android:state_checkable:boolean类型。表示控件是不是是可检勾选的(仅适用于可勾选的控件)。
– android:state_checked:boolean类型。表示控件是不是处于勾选状态(仅适用于可勾选的控件)。
– android:state_enabled:boolean类型。表示控件是不是处于使能状态(便可以接受 touch/click事件)。
– android:state_window_focused:boolean类型。表示利用窗口是不是处于具有焦点(利用在前台)。
举例:
android:color="#ffff0000"/>
android:color="#ff0000ff"/>
在Button中援用该资源:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/button_text"
android:textColor="@color/button_text" />
Style资源(Style Resource)
Style资源用于定义UI的样式。1个样式可以作用某个View上,也能够作用在全部Activity乃至是Application上。如需了解样式和主题的官方介绍,您可以点击这个链接:《Styles and Themes》。
!请注意:style是1个单独的资源,如需援用该资源,需要援用的是name属性中定义的名字,而不是XML文件的名字。所以,您可以将所有的style资源都定义在1个XML文件中,并将标签作为根标签。
文件目录:
res/values/filename.xml
援用方式:
In XML: @[package:]style/style_name
语法:
parent="@[package:]style/style_to_inherit">
name="[package:]style_property_name"
>style_value
标签及其属性:
:不可缺省,且必须是根标签。无属性。
– name:String类型,不可缺省。样式的名字。Activity、Application或View所援用的ID就是这个名字。
– parent:Style 资源。继承其他style资源。
:为style定义1个属性。必须是
– name :属性资源,不可缺省。用于定义某个属性,如android:textColor。
示例:
<?xml version="1.0" encoding="utf⑻"?>
#008
将上述style利用于TextView上:
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello, World!" />
String资源(String Resources)
用于为利用程序提供字符串资源。有以下3种字符串的格式:
String:用于提供1个单独的字符串;
String Array:用于提供1个字符串数组;
Quantity Strings (Plurals):用于提供复数的字符串(carries different strings for pluralization)。
单独的字符串资源(String)
字符串资源可以被Java程序或XML文件援用。
!请注意:String是1个单独的资源,如需援用该资源,需要援用的是name属性中定义的名字,而不是XML文件的名字。所以,您可以将所有的String资源都定义在1个XML文件中,并将标签作为根标签。
文件目录:
res/values/filename.xml
援用方式:
In Java: R.string.string_name
In XML:@string/string_name
语法:
text_string
标签及其属性:
:不可缺省,必须为根标签。无属性。
:值为您所指定的字符串内容。
– name :String类型。字符串的键。通过ID援用的就是这个键。
示例:
Hello!
援用上述字符串资源:
android:layout_height="wrap_content"
android:text="@string/hello" />
在Java中援用上述资源:
String string = getString(R.string.hello);
字符串数组资源(String Array)
1个字符串数组资源,可以在程序中援用。
!请注意:String Array是1个单独的资源,如需援用该资源,需要援用的是name属性中定义的名字,而不是XML文件的名字。所以,您可以将所有的String Array资源都定义在1个XML文件中,并将标签作为根标签。
文件目录:
res/values/filename.xml
援用方式:
In Java: R.array.string_array_name
语法:
text_string
标签及其属性:
:不可缺省,且必须是根标签。无属性
:定义了1组字符串资源。每个字符串用1个标签包括。
– name:String类型。字符串数组的键。程序中的ID就是该键。
:String类型。用于定义1个字符串。必须包括在标签内。无属性。
示例:
Mercury
Venus
Earth
Mars
在代码中援用该字符串数组资源:
Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);
复数的字符串资源(Quantity Strings (Plurals))
不同的语言在单复数上具有不同的语法规则。在英语中,1表示单数,如“1 book”,大于1表示复数,如“n books”,这类单复数的的区分在英语中很常见,而其他语言在单复数的处理上与英语的语法又有很大区分(如中文语法没有明显体现复数的概念)。为了支持不同语言的单复数规则,Android提供了zero、one、 two、 few、 many、 other等枚举值。
Android提供了getQuantityString()方法来选择适合的单复数资源。
复数的字符串资源只能用于复数。
!请注意:Quantity Strings是1个单独的资源,如需援用该资源,需要援用的是name属性中定义的名字,而不是XML文件的名字。所以,您可以将所有的Quantity Strings资源都定义在1个XML文件中,并将标签作为根标签。
文件目录:
res/values/filename.xml
援用方式:
In Java: R.plurals.plural_name
语法:
text_string
标签及其属性:
:不可缺省,且必须作为根标签。无属性。
:1个字符串的集合。该标签中包括若干个标签。
– name:String类型。援用该资源的键。程序ID援用的就是这个键。
:包括1个单数或复数的字符串。值可以援用其他字符串资源。
– quantity:为以下若干Value值。
Value
Description
zero
在某种语言中,当末尾数字为0时,需要特殊处理。如阿拉伯语。
one
在某种语言中,当末尾数字为1时,需要特殊处理。如英语和其他大多数语言;在俄语中,除11之外的其他以1结尾的数字,属于这1类型。
two
在某种语言中,当末尾数字为2时,需要特殊处理。如威尔士语中的2;斯洛文尼亚语中的102。
few
在某种语言中,较小的数字需要特殊处理。如捷克语中的2、3、4;波兰语中除12、13、14之外,以2、3、4结尾的数字。
many
在某种语言中,较大的数字需要特殊处理。如马耳他语中以11⑼9结尾的数字。
other
在某种语言中,并没有明显的单复数概念。如中文。
示例:
%d song found.
%d songs found.
Znaleziono %d piosenkę.
Znaleziono %d piosenki.
Znaleziono %d piosenek.
在Java中援用资源:
int count = getNumberOfsongsAvailable();
Resources res = getResources();
String songsFound = res.getQuantityString(R.plurals.numberOfSongsAvailable, count, count);
需要注意的是,如果您援用的XML文件中包括了格式化的字符(如%d),那末需要在getQuantityString()方法中传入3个参数。其中第2个参数用于让系统决定应当选择哪一个item标签中的资源,而第3个参数是1个可变数组,用于替换格式化的字符(如%d)。如果您在字符串资源中未指定格式化的字符,那末可以不传入第3个参数。
设计您的字符串资源(Formatting and Styling)
转义单引号和双引号(Escaping apostrophes and quotes)
如果您的字符串中包括了单引号(’),那末需要在单引号前加1个反斜杠(\),以便在字符串中能正确辨认这个单引号;或直接用双引号包括全部字符串,以下所示:
This\'ll work
"This'll also work"
This doesn't work
如果您的字符串中包括了双引号(”),那末需要在双引号前加1个反斜杠(\),以便在字符串中能正确辨认这个双引号。但是,用双引号包括全部字符串的方式不再可行:
This is a \"good string\".
This is a "bad string".
'This is another "bad string".'
格式化字符串(Formatting strings)
通过调用String.format(String, Object...)方法,可以将字符串进行格式化。如:
Hello, %1$s! You have %2$d new messages.
上述字符串中,%1$s表示1个字符串,%2$d表示1个10进制数。由于format()方法中的第2个参数是1个可变数组,您可以将参数传入其中以替换这些转义字符:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
使用HTML标记语言定制字符串样式(Styling with HTML markup)
如:
Welcome to Android!
Android支持的HTML标签包括:
表示文本加粗;
表示斜体;
表示添加下划线。
为了使HTML标签生效,需要使用转义的HTML字符:
Hello, %1$s! You have <b>%2$d new messages</b>.
其中,左尖括号(”
接着调用fromHtml(String)方法,使HTML标签生效。
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
CharSequence styledText = Html.fromHtml(text);
调用htmlEncode()方法确保传入的字符串参数已被转义,由于只有被转义后的字符串才能使HTML标签生效:
String escapedUsername = TextUtil.htmlEncode(username);
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount);
CharSequence styledText = Html.fromHtml(text);
使用Spannables样式(Styling with Spannables)
Spannables可以将若干不一样式(如色彩、字号)的文本对象拼接在1起:
/**
* Returns a CharSequence that concatenates the specified array of CharSequence
* objects and then applies a list of zero or more tags to the entire range.
*
* @param content an array of character sequences to apply a style to
* @param tags the styled span objects to apply to the content
* such as android.text.style.StyleSpan
*
*/
private static CharSequence apply(CharSequence[] content, Object... tags) {
SpannableStringBuilder text = new SpannableStringBuilder();
openTags(text, tags);
for (CharSequence item : content) {
text.append(item);
}
closeTags(text, tags);
return text;
}
/**
* Iterates over an array of tags and applies them to the beginning of the specified
* Spannable object so that future text appended to the text will have the styling
* applied to it. Do not call this method directly.
*/
private static void openTags(Spannable text, Object[] tags) {
for (Object tag : tags) {
text.setSpan(tag, 0, 0, Spannable.SPAN_MARK_MARK);
}
}
/**
* "Closes" the specified tags on a Spannable by updating the spans to be
* endpoint-exclusive so that future text appended to the end will not take
* on the same styling. Do not call this method directly.
*/
private static void closeTags(Spannable text, Object[] tags) {
int len = text.length();
for (Object tag : tags) {
if (len > 0) {
text.setSpan(tag, 0, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} else {
text.removeSpan(tag);
}
}
}
/**
* Returns a CharSequence that applies boldface to the concatenation
* of the specified CharSequence objects.
*/
public static CharSequence bold(CharSequence... content) {
return apply(content, new StyleSpan(Typeface.BOLD));
}
/**
* Returns a CharSequence that applies italics to the concatenation
* of the specified CharSequence objects.
*/
public static CharSequence italic(CharSequence... content) {
return apply(content, new StyleSpan(Typeface.ITALIC));
}
/**
* Returns a CharSequence that applies a foreground color to the
* concatenation of the specified CharSequence objects.
*/
public static CharSequence color(int color, CharSequence... content) {
return apply(content, new ForegroundColorSpan(color));
}