在LayerDrawable中旋转单个RotateDrawable

时间:2012-02-04 14:51:13

标签: android

我正在构建一个包含某种指南针的应用程序,我想使用LayerDrawable绘制并为指南针设置动画。 LayerDrawable包含罗盘背景的静态背景图像和旋转部件的RotateDrawable。这是我的可绘制资源的XML代码:

compass_text.xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android" 
    android:drawable="@drawable/compasstext"
    android:fromDegrees="0"
    android:toDegrees="360"
    android:pivotX="50%"
    android:pivotY="50%" />

compass_layers.xml:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/compassbackground" />
    <item android:drawable="@drawable/compass_text" />
</layer-list>

LayerDrawable显示得很好,但我该如何旋转呢?这是我试过的代码:

compassText = (RotateDrawable)getResources().getDrawable(R.drawable.compass_text);
compassText.setLevel(5000);

这没有任何作用。我做错了什么?

1 个答案:

答案 0 :(得分:3)

您需要确保在设置级别之前获得膨胀的特定Drawable,而不是资源中的通用Drawable对象。试试这个:

ImageView iv = (ImageView) findViewById(R.id.xxx); ////where xxx is the id of your ImageView (or whatever other view you are using) in your xml layout file
LayerDrawable lv = (LayerDrawable) iv.getDrawable();
compassText = (RotateDrawable) lv.getDrawable(1); //1 should be the index of your compassText since it is the second element in your xml file

compassText.setLevel(5000);