如何在Android中添加视图动画?

maz*_*a23 15 animation android

我想知道是否有一种简单的方法可以将视图(按钮)添加到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);
    }
Run Code Online (Sandbox Code Playgroud)

然后尝试将此按钮添加到视图,它不起作用.请帮忙!

Ric*_*tte 15

在您的活动中,请改用:

parentview.addView(myButton);
Run Code Online (Sandbox Code Playgroud)

然后用以下方法为按钮设置动画:

Animation animation = AnimationUtils.loadAnimation(getBaseContext(), R.anim.slide_right_in);
animation.setStartOffset(0);
myButton.startAnimation(animation);
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

另外,这是我写的一个活动播放动画功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

您可以这样调用:

PlayAnim(R.id.bottombar, (Context) this, R.anim.slide_right_in, 0);
Run Code Online (Sandbox Code Playgroud)

哪里:

第一个参数是要应用动画的视图的ID.

第二个参数是在您的活动中检索的上下文.

第3个参数是您放置在动画资源文件夹或android预定义动画中的所需动画.

第4个参数是动画的startoffset.

  • 我找不到你说的你想要在代码中完成所有这些,对不起. (5认同)

Tom*_*mik 7

我测试了你的动画按钮实现,它工作正常.一定有其他一些问题.可能是您将按钮添加到布局的方式.

要将按钮添加到相对布局,请使用此类代码.

RelativeLayout rl = (RelativeLayout)findViewById(R.id.rl);
MyButton b1 = new MyButton(Main.this);
b1.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
rl.addView(b1);
Run Code Online (Sandbox Code Playgroud)

或者您可以从布局中膨胀按钮.为此,请创建mybtn.xml包含按钮实现的布局:

<?xml version="1.0" encoding="utf-8"?>
<PACKAGE_OF_MYBUTTON_HERE.MyButton
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  />
Run Code Online (Sandbox Code Playgroud)

要将其添加到布局调用中:

RelativeLayout rl = (RelativeLayout)findViewById(R.id.rl);
Button b = (Button)getLayoutInflater().inflate(R.layout.mybtn, rl, false);
rl.addView(b);
Run Code Online (Sandbox Code Playgroud)

将视图添加到相对布局时,视图的正确定位可能存在问题.只需在调用之前添加这样rl.addView(b1)的代码(代码片段在someOtherView下面添加新按钮).

LayoutParams lp = new LayoutParams(b.getLayoutParams());
lp.addRule(RelativeLayout.BELOW, someOtherView.getId());
b.setLayoutParams(lp);
Run Code Online (Sandbox Code Playgroud)