简体   繁体   中英

Animating a custom view with button onClick()

So i have created a Custom class that extends View. My onDraw() in this class is the following:

@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();
}

Main Activity:

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!

    }
}

And finally the rotation 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>

I simply add a Bitmap and some text. What I want to do in my main activity is to rotate the whole CustomView in one animation on a single buttonclick but i just can't get it to work! I have tried several animations solutions but i keep getting crashes whenever i start the animation.

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

Any help is much appreciated!

there's a simple solution.On button click just start your animation like below.Just replace view with your view name. view.animate().rotation(360).setDuration(1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM