Android - 以编程方式过渡背景渐变?

时间:2014-08-02 11:30:15

标签: android android-layout android-activity

我有两个渐变可绘制文件(其中一个示例):

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape>
      <gradient
        android:angle="90"
        android:startColor="#DBDBDB"
        android:endColor="#F0F0F0"
        android:type="linear" />
    </shape>
  </item>
</selector>

我有一个可过渡的过渡:

<?xml version="1.0" encoding="UTF-8"?>
  <transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/gradient_c" />
    <item android:drawable="@drawable/gradient_e" />
  </transition>

我想以编程方式将活动的背景从gradient_c淡化为gradient_e(并反转等)。我正在使用此代码:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlRAM); TransitionDrawable transition = (TransitionDrawable) rl.getBackground(); // TransitionDrawable transition = (TransitionDrawable) getWindow().getDecorView().getBackground(); transition.startTransition(500);

但是,当我尝试运行代码时出现错误:
08-02 12:04:32.223: E/AndroidRuntime(12646): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blogspot.appsversatile.performancer/com.example.app.RAM}: java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.TransitionDrawable

我只是想将活动的背景淡化为另一个渐变(来自可绘制文件)。我怎样才能做到这一点?



我已经接受了下面的答案,因为他给了我答案,但这篇文章没有准确解释。 我解决这个问题的方法是将我的RelativeLayout背景应用于过渡drawable: android:background="@drawable/transition

我刚才用过:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlRAM); TransitionDrawable transition = (TransitionDrawable) rl.getBackground(); transition.startTransition(500);

1 个答案:

答案 0 :(得分:4)

StackTrace解释说您正在尝试将StateListDrawabl强制转换为TransitionDrawable。这无法完成。

(TransitionDrawable) rl.getBackground();
java.lang.ClassCastException: android.graphics.drawable.StateListDrawable cannot be cast to android.graphics.drawable.TransitionDrawable

您正在使用StateListDrawable,因此您应该使用类似:

的内容
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rlRAM);
StateListDrawable drawable = (StateListDrawable) rl.getBackground();
TransitionDrawable transition = (TransitionDrawable) drawable.getCurrent();
transition.startTransition(500);