Reputation: 65
I want to create a ball every time someone touches the screen, but i can't seem to get it to work. I want it to be created in a certain location and spawn a ball. There is an if statement which sees if there is a tap on the screen, and in the if statement it calls the draw that is made below to draw a circle in the window.
package com.example.madusha.gravityball;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
public class GameWindow extends Activity {
private Paint paint;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_window);
Button pause = (Button) findViewById(R.id.pausebutton);
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
Intent intent = new Intent(GameWindow.this, PauseMenu.class);
startActivity(intent);
}
});
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
int Action = event.getAction();
if(Action == KeyEvent.ACTION_DOWN){
onDraw();
System.out.println("Works???");
return true;
}
return super.onKeyDown(keyCode,event);
}
public void init() {
paint = new Paint();
paint.setColor(Color.BLUE);
}
Canvas canvas;
public void onDraw(){
init();
int height = 100;
int width = 100;
canvas.drawCircle(width, height,100,paint);
}
}
Upvotes: 0
Views: 73
Reputation: 91
Drawing to a canvas can only be done inside a View
object, not an activity like the one that you have in the example. You could create your own custom view something like this -
public class CustomView extends View {
private Paint paint;
public CompletionSliderView(Context context) {
super(context);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLUE);
}
@Override
protected void onDraw(Canvas canvas) {
int height = getMeasuredHeight();
int width = getMeasuredWidth();
canvas.drawCircle(width/2, height/2, height/2, paint);
}
}
To use this in an xml layout, you will need to do this, replacing the package name (probably com.yourcompany.yourapp
).
<com.yourcompany.yourapp.CustomView
android:layout_width="64dp"
android:layout_height="64dp"/>
You can create a new view in code by doing
View circle = new CustomView(getContext());
Then you can add this to your layout.
Upvotes: 1
Reputation: 135
You need to use the OnDraw() function. That is what updates the canvas when drawing stuff.
Upvotes: 1