关于更改ImageButton的ImageBitmap的动画

hun*_*eva 2 android android-animation

假设我有一个ImageButton btn.我有两个不同的Bitmap,bmp1bmp2.默认情况下,btn显示bmp1如下:

btn.setImageBitmap(bmp1);
Run Code Online (Sandbox Code Playgroud)

我可以以某种方式制作动画,交叉淡化,bmp1bmp2在调用以下内容时:

btn.setImageBitmap(bmp2);
Run Code Online (Sandbox Code Playgroud)

所以问题是,是否有可能 - 如果是,如何 - 为ImageButtons上的位图更改设置动画?

Squ*_*gem 7

我看到它的方式,实现此功能有两种主要方式.请注意,可能有其他方法可以完全按照您的描述进行此操作,但这些方法将是我的方法.

第一种方法:利用onAnimationEnd()回调

在这里,您希望基本上淡出第一个ImageButton,更改onAnimationEnd()回调中的资源,然后将其淡入.为此,您必须实现以下代码.

  1. Animation使用XML 创建一个用于淡入的资源View:

    <!-- Filename: fadein.xml -->
    <set xmlns:android="http://schemas.android.com/apk/res/android"> 
    <!-- Note that you might want to change the duration here-->
    <alpha 
        android:fromAlpha="0.0" 
        android:toAlpha="1.0"  
        android:duration="250"/> 
    </set>   
    
    Run Code Online (Sandbox Code Playgroud)
  2. Animation使用XML 创建一个用于淡化View输出的资源:

    <!-- Filename: fadeout.xml -->
    <set xmlns:android="http://schemas.android.com/apk/res/android"> 
    <!-- Note that you might want to change the duration here-->
    <alpha 
        android:fromAlpha="1.0" 
        android:toAlpha="0.0"  
        android:duration="250"/> 
    </set>
    
    Run Code Online (Sandbox Code Playgroud)
  3. Animation在代码中加载淡出和淡入s:

    // Obtain a reference to the Activity Context
    Context context = getContext();
    
    // Create the Animation objects.
    Animation outAnimation = AnimationUtils.loadAnimation(context, R.anim.fadeout);
    Animation inAnimation = AnimationUtils.loadAnimation(context, R.anim.fadein);
    
    Run Code Online (Sandbox Code Playgroud)
  4. AnimationListener为此分配一个新的Animation,并按如下方式构建它:

    outAnimation.setAnimationListener(new AnimationListener(){
    
        // Other callback methods omitted for clarity.
    
        public void onAnimationEnd(Animation animation){
    
            // Modify the resource of the ImageButton
            yourImageButton.setImageResource(R.drawable.[your_second_image]);
    
            // Create the new Animation to apply to the ImageButton.
            yourImageButton.startAnimation(inAnimation);                                           
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. 分配AnimationImageButton,然后开始第一个Animation:

    yourImageButton.startAnimation(outAnimation);
    
    Run Code Online (Sandbox Code Playgroud)
  6. 然后,如果您希望动画回到上一个图像,您只需执行相同的操作,但顺序相反.

第二种方法:叠加一秒 ImageButton

对于这种方法,您只需将两个ImageButtons 分配给屏幕上的相同坐标,并使用相同的宽度.然后,你会淡出第一个ImageButton并在第一个结束后淡入第二个Animation(很像上面的例子).


我希望这个答案符合你的期望.如果有任何代码错误,我很抱歉,因为我现在没有编辑器这样做.如果您需要任何其他说明,请告诉我们!