在LayerDrawable中旋转单个RotateDrawable



我正在构建一个包含某种指南针的应用程序,我想使用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);

这毫无作用。我做错了什么?

您需要确保在设置级别之前获得膨胀的特定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);

最新更新