2010-08-25 15 views
6

我试图创建一个具有自定义选择器的透明(无按钮背景)ImageButton。我有选择器工作的按钮,但我现在希望选择器drawables交叉淡入对方。 我看到了可以用XML表示的TransitionDrawable对象。有没有办法将它连接到我的选择器?在Android中使用转换的ImageButton

以下是在屏幕左下角的屏幕上创建图像按钮的XML布局代码。它目前从一个图像到下一个突然忽略过渡XML。

selector_button.xml

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:state_pressed="true" android:drawable="@drawable/transition_normal_to_pressed" /> <!-- pressed --> 
    <item android:state_focused="true" android:drawable="@drawable/transition_pressed_to_normal" /> <!-- focused --> 
    <item android:drawable="@drawable/menu_normal" /> <!-- default --> 
</selector> 

transition_normal_to_pressed.xml

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

activity.xml

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <ImageButton 
     android:id="@+id/btnMenu" 
     android:background="@android:color/transparent" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/selector_button" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentBottom="true" /> 
</RelativeLayout> 

回答

6

您需要放下选择器,并直接使用过渡作为ImageButtons drawable。动画本身必须在代码

ImageButton button = (ImageButton) findViewById(R.id.button); 
TransitionDrawable drawable = (TransitionDrawable) button.getDrawable(); 
drawable.startTransition(500); 

被应用在哪里drawable.reverseTransition(500)将扭转其当前状态的转变。

参见Transition Drawable以及TransitionDrawable.html#reverseTransition(int)作进一步解释。

4

在选择使用过渡

ImageButton button = (ImageButton) findViewById(R.id.button); 
Drawable d = button.getDrawable.getCurrent(); //or AnyView.getBackground().getCurrent(); for custom background 
     if (d instanceof TransitionDrawable) { 
      TransitionDrawable t = (TransitionDrawable) d; 
      t.startTransition(500); 
     } 
2

答案上面太复杂,试试这个

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android" 
android:exitFadeDuration="240" 
android:enterFadeDuration="120" > 
<item android:state_pressed="true" 
    android:drawable="@color/pressed_bg" /> 
<item android:state_pressed="false" 
    android:drawable="@android:color/transparent" /> 
</selector> 
+0

属性 “exitFadeDuration” 和 “enterFadeDuration” API级别仅用于11和更高 – 2014-10-21 18:52:28