This question already has an answer here:
I am new to Android Studio and am working on getting a ball responds to tilt. I got some code written down and when I trying to run it, it throws me an error like that. Thanks in advance!
AnimatedView.java
package com.example.android.ballpls; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.widget.ImageView; public class AnimatedView extends ImageView { private Context mContext; int x = -1; int y = -1; private int xVelocity = 10; private int yVelocity = 5; private Handler h; private final int FRAME_RATE = 30; public AnimatedView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; h = new Handler(); } private Runnable r = new Runnable() { @Override public void run() { invalidate(); } }; protected void onDraw(Canvas c) { BitmapDrawable ball = (BitmapDrawable) ContextCompat.getDrawable(getContext(), R.drawable.ball); if (x < 0 && y < 0) { x = this.getWidth() / 2; y = this.getHeight() / 2; } else { x += xVelocity; y += yVelocity; if ((x > this.getWidth() - ball.getBitmap().getWidth()) || (x < 0)) { xVelocity = xVelocity * -1; } if ((y > this.getHeight() - ball.getBitmap().getHeight()) || (y < 0)) { yVelocity = yVelocity * -1; } } c.drawBitmap(ball.getBitmap(), x, y, null); h.postDelayed(r, FRAME_RATE); }
MainActivity.java
package com.example.android.ballpls; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
No comments:
Post a Comment