开发者

Casting a datatype in Android

Resources myResources = getResources();

CharSequence styledText = myResources.getText开发者_如何学Python(R.string.stop_message); Drawable icon = myResources.getDrawable(R.drawable.app_icon);

int opaqueBlue = myResources.getColor(R.color.opaque_blue);

float borderWidth = myResources.getDemension(R.dimen.standard_border);

Animation tranout = AnimationUtils.loadAnimation(this, R.anim.spin_shrink_fade);

String{} stringArray = myResources.getStringArray(R.array.string_array);

int[] intArray = myResources.getIntArray(R.array.integer_array);

Resources myResources = getResources(); AnimationDrawable rocket = (AnimationDrawable)myResources.getDrawable (R.drawable.frame_by_frame);

I'm comparing the last couple statements with the proceeding ones. My question is why is AnimationDrawable explicitly cast when in the other examples above no casting is required?


Because AnimationDrawable extends Drawable (indirectly).

myResources.getDrawable returns a type of Drawable, which must be cast in order to be assigned to a type of AnimationDrawable.

Basically AnimationDrawable is indirectectly a type of Drawable, which means that Drawable variables can point to Drawable types and its children types (including AnimationDrawable). This doesn't work in reverse, for example, you can't assign a type of Drawable to a variable that points to AnimationDrawable in the same way you can't assign a type of Drawable to a variable pointing to a LevelListDrawable (another type of Drawable).

See this page for more info: http://developer.android.com/reference/android/graphics/drawable/DrawableContainer.html

And this page for more general info: http://www.javabeginner.com/learn-java/java-inheritance


because there are lots of kinds of drawbles, depending on what you request you get different types, all inheriting from the generic drawable ancestor. Unless you only care about the generic Drawable methods and members, you have to know the type of what you're asking for and cast the generic Drawable to that specific type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜