【发布时间】:2013-03-27 10:38:59
【问题描述】:
我想在 Android 中创建一个带有文本和背景图像的按钮。背景图像应每 X 次淡入淡出。
我使用带有 2 张图像的 TransitionDrawable 进行这项工作。
但我不能让它处理超过 2 个图像。
我有什么:
在 Java 代码中,我创建了一个 Button 并设置了一个背景(这是一个在 XML 中定义的 TransitionDrawable)。然后我开始过渡。
final Button b = new Button(getApplicationContext());
b.setTextColor(getResources().getColor(R.color.white));
b.setText("Some text");
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.tile));
StateListDrawable background = (StateListDrawable) b.getBackground();
TransitionDrawable td = (TransitionDrawable) background.getCurrent();
td.startTransition(2000);
在 XML 中我在 tile.xml 中定义
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<solid
android:color="#449def" />
</shape>
</item>
<item android:drawable="@drawable/transition">
<shape>
<solid
android:color="#0000ff" />
</shape>
</item>
</selector>
最后是一个transition.xml
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
<item android:drawable="@drawable/desert"/>
<item android:drawable="@drawable/hydrangeas" />
<item android:drawable="@drawable/jellyfish" />
</transition>
现在效果是,当我启动应用程序时,会显示沙漠图像。该图像按应有的方式淡入绣球花图像。但水母图像从未显示。
在TransitionDrawables 的文档中指出,您可以指定超过2 个可绘制对象,但我无法让它工作。
我也试过这个没有任何 XML 但在纯 JAVA 中但这给出了完全相同的问题:-(
【问题讨论】:
-
TransitionDrawables 的文档中声明您可以指定 2 个以上的可绘制对象 - 您能提供一个链接到说明的地方吗?
-
developer.android.com/reference/android/graphics/drawable/… 这表明“此可绘制对象至少需要 2 层才能正常工作。”。正如我在原始帖子中所说,我还尝试了纯 Java 代码中的所有内容(因此实际上使用了这个构造函数),但这有完全相同的问题。
-
单词的错误选择。我刚刚查看了
TransitionDrawable的代码,它只在两个可绘制对象之间淡入淡出,所有其他图层都被忽略了。 -
感谢 Luksprog 在这种情况下,我会做一些变通方法来实现我想要的。
-
也许你可以简单地使用两个TransitionDrawables,一个包含第一个和第二个drawable,另一个包含相同的第二个drawable和第三个drawable。