使用onClick()按钮设置自定义视图的动画

时间:2018-04-24 15:59:51

标签: java android animation

所以我创建了一个扩展View的Custom类。 我在这个类中的onDraw()如下:

@Override
protected void onDraw(Canvas canvas) {
    Bitmap myBitmap = BitmapFactory.decodeResource (getResources(), R.drawable.image);
    super.onDraw(canvas);
    final Paint paint = new Paint();
    paint.setTextSize(100);
    paint.setColor(Color.BLUE);
    canvas.drawBitmap(myBitmap, 10, 10, paint);
    canvas.drawText(date,  200, 200, paint);
    invalidate();
}

主要活动:

public class MainActivity extends AppCompatActivity{

    private Button animateBtn;
    private ImageView image;
    private Animation anim;
    private Calendar calendar;
    private Customclass cc;
    private Animation animation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        cc = new Customclass(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionbar = getSupportActionBar();
        actionbar.setDisplayShowHomeEnabled(true);
        actionbar.setIcon(R.mipmap.launcher_icon);

        // Create the view and add it to the layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.myLayout);
        rl.addView(cc);
    }

    public void startAnim(View v){
        Customclass customclass = (Customclass ) findViewById(R.id.custom_view);
        Animation animation = AnimationUtils.loadAnimation(this,R.anim.rotation);
        customclass.startAnimation(animation); //<- crashes here!

    }
}

最后旋转xml:

<?xml version="1.0" encoding="utf-8"?>
<rotate android:pivotY="50%"
    android:pivotX="50%"
    android:toDegrees="1080"
    android:fromDegrees="0"
    android:duration="3000"
    xmlns:android="http://schemas.android.com/apk/res/android">
</rotate>

我只需添加一个位图和一些文字。我想在我的主要活动中做的是在一个按钮上单击一个动画旋转整个CustomView,但我无法让它工作! 我已经尝试了几种动画解决方案,但每当我开始动画时我都会崩溃。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.lab3.Customclass .startAnimation(android.view.animation.Animation)' on a null object reference

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

有一个简单的解决方案。点击按钮就可以像下面一样启动动画。只需用您的视图名称替换视图。 view.animate().rotation(360).setDuration(1000);