android - 如何在 Android 中为添加 View 设置动画?

标签 android animation

我想知道是否有一种简单的方法可以将 View (按钮)添加到 RelativeLayout,并带有某种比例动画。 我从 Button 扩展了一个类并做了这样的事情:

    public class MyButton extends Button {

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        ScaleAnimation anim = new ScaleAnimation(0,1,0,1);
        anim.setDuration(1000);
        anim.setFillAfter(true);
        this.startAnimation(anim);
    }

然后尝试将此按钮添加到 View 中,但没有成功。请帮忙!

最佳答案

在您的 Activity 中,改用:

parentview.addView(myButton);

然后用这个动画按钮:

Animation animation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.slide_right_in);
animation.setStartOffset(0);
myButton.startAnimation(animation);

这是 slide_right_in.xml 的一个例子

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="100%p" android:toXDelta="0" android:duration="800"/>
</set>

此外, 这是我写的一个activity播放动画函数:

public Animation PlayAnim( int viewid, Context Con, int animationid, int StartOffset )
{
    View v = findViewById(viewid);

    if( v != null )
    {
        Animation animation = AnimationUtils.loadAnimation(Con, animationid  );
        animation.setStartOffset(StartOffset);
        v.startAnimation(animation);

        return animation;
    }
    return null;
}

你可以这样调用它:

PlayAnim(R.id.bottombar, (Context) this, R.anim.slide_right_in, 0);

地点:

第一个参数是要应用动画的 View 的 ID。

第二个参数是在您的 Activity 中检索到的上下文。

第三个参数是您放入动画资源文件夹或来自 android 预定义动画的所需动画。

第四个参数是动画开始偏移量。

关于android - 如何在 Android 中为添加 View 设置动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7432375/

相关文章:

java - 膨胀 MaterialAnimatedSwitch 时出错

java - UnsupportedOperationException 音频效果 : invalid parameter operation

animation - 在 SVG 悬停时触发 SVG 动画

ios - 为什么 ImageView.StartAnimating 不会在主线程上设置动画

javascript - asp.net 页面重新加载 javascript onclick 函数

css - 暂停 css3 关键帧动画

安卓 : how to execute AsyncTask?

java - 使用 Processing 在 Android SDK 中编译 build.xml 时出现问题

android - 适用于企业的 Google 移动 SDK

ios - 流畅地动画化 UISlider