how to make a circle slowly "pop" onto the screen - java

Im making an app that displays multiple random circles on the screen. I want to know if i can expand the radius WHILE it is displaying the circle then disapeers. I have already written the code to randomly display the circles here it is.
public class SplashLaunch extends View{
Handler cool = new Handler();
DrawingView v;
ObjectAnimator aa = new ObjectAnimator();
Paint newPaint = new Paint();
int randomWidthOne = 0;
int randomHeightOne = 0;
private static int radiusOne = 300;
final int redColorOne = Color.RED;
final int greenColorOne = Color.GREEN;
private static int lastColorOne;
private final Random theRandom = new Random();
public SplashLaunch(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
private final Runnable circleUpdater = new Runnable() {
#SuppressLint("NewApi")
#Override
public void run() {
lastColorOne = theRandom.nextInt(2) == 1 ? redColorOne : greenColorOne;
newPaint.setColor(lastColorOne);
cool.postDelayed(this, 500);
int x = 0;
while(x<=255){
newPaint.setAlpha(x);
x++;
}
invalidate();
}
};
#Override
protected void onAttachedToWindow(){
super.onAttachedToWindow();
cool.post(circleUpdater);
}
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
cool.removeCallbacks(circleUpdater);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if(theRandom == null){
randomWidthOne =(int) (theRandom.nextInt(Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}else {
randomWidthOne =(int) (theRandom.nextInt(Math.abs(getWidth()-radiusOne/2)) + radiusOne/2f);
randomHeightOne = (theRandom.nextInt((int)Math.abs((getHeight()-radiusOne/2 + radiusOne/2f))));
}
canvas.drawCircle(randomWidthOne, randomHeightOne, radiusOne, newPaint);
}
}

I want to know if i can expand the radius WHILE it is displaying the circle then disappears
Yes you can. You simply animate the Scale of your view to a value greater than 1 to expand the view then back to 0 to make it "disappear".

Related

Intersect method not working, keeps returning true

My intersect method keeps returning true and setting my "score text" to intersect detected when my images do not collide, instead it changes the text as soon as the emulator starts. Please notify me if more code is needed and check back within 10 minutes. Thanks! -this is all my code and collision code starts at line 163, something is wrong with my collision code because collision isn't being detected, what should I do to fix my collision code.
here is my code:
public class MainActivity extends AppCompatActivity {
//Layout
private RelativeLayout myLayout = null;
//Screen Size
private int screenWidth;
private int screenHeight;
//Position
private float ballDownY;
private float ballDownX;
//Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Images
private ImageView net = null;
private ImageView ball = null;
//for net movement along x-axis
float x;
float y;
//points
private int points = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLayout = (RelativeLayout) findViewById(R.id.myLayout);
//score
TextView score = (TextView) findViewById(R.id.score);
//imageviews
net = (ImageView) findViewById(R.id.net);
ball = (ImageView) findViewById(R.id.ball);
//retrieving screen size
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
//move to out of screen
ball.setX(-80.0f);
ball.setY(screenHeight + 80.0f);
//start timer
timer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
changePos();
}
});
}
}, 0, 20);
}
public void changePos() {
//down
ballDownY += 10;
if (ball.getY() > screenHeight) {
ballDownX = (float) Math.floor((Math.random() * (screenWidth -
ball.getWidth())));
ballDownY = -100.0f;
}
ball.setY(ballDownY);
ball.setX(ballDownX);
/*INTERSECT METHOD
Rect rc1 = new Rect();
net.getDrawingRect(rc1);
Rect rc2 = new Rect();
ball.getDrawingRect(rc2);
if (Rect.intersects(rc1, rc2)) {
TextView score = (TextView) findViewById(R.id.score);
score.setText("INTERSECT DETECTED");
}*/
//make net follow finger
myLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
MainActivity.this.x = event.getX();
y = event.getY();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
net.setX(MainActivity.this.x);
net.setY(y);
}
return true;
}
});
}
public boolean Collision(ImageView net, ImageView ball)
{
Rect AR = new Rect();
net.getHitRect(AR);
Rect BR = new Rect();
ball.getHitRect(BR);
Render();
return AR.intersect(BR) || AR.contains(BR) || BR.contains(AR);
}
public void Render()
{
if(Collision(net, ball))
{
points++;
TextView score = (TextView)findViewById(R.id.score);
score.setText("Score:" + points);
}
}
}
I have reformed your code, try now
public class MainActivity extends AppCompatActivity
{
//Layout
private RelativeLayout myLayout = null;
//Screen Size
private int screenWidth;
private int screenHeight;
//Position
private float ballDownY;
private float ballDownX;
//Initialize Class
private Handler handler = new Handler();
private Timer timer = new Timer();
//Images
private ImageView net = null;
private ImageView ball = null;
//score
private TextView score = null;
//for net movement along x-axis
public float x = 0;
public float y = 0;
//points
private int points = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
this.myLayout = (RelativeLayout) findViewById(R.id.myLayout);
this.score = (TextView) findViewById(R.id.score);
this.net = (ImageView) findViewById(R.id.net);
this.ball = (ImageView) findViewById(R.id.ball);
//retrieving screen size
WindowManager wm = getWindowManager();
Display disp = wm.getDefaultDisplay();
Point size = new Point();
disp.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
//move to out of screen
this.ball.setX(-80.0f);
this.ball.setY(screenHeight + 80.0f);
//Error here
/*//Run constantly
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Render();
}
}, 100); //100 is miliseconds interval than sleep this process, 1000 miliseconds is 1 second*/
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(100);
runOnUiThread(new Runnable() {
#Override
public void run(){Render();}});}
}catch (InterruptedException e) {}}};
t.start();
}
public void Render()
{
changePos();
if(Collision(net, ball))
{
points++; //You dont need findView Textview score for that exists in OnCreate Method
this.score.setText("Score:" + points);
}
}
public void changePos()
{
//down
ballDownY += 10;
if (ball.getY() > screenHeight) {
ballDownX = (float) Math.floor((Math.random() * (screenWidth - ball.getWidth())));
ballDownY = -100.0f;
}
ball.setY(ballDownY);
ball.setX(ballDownX);
//make net follow finger
myLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
x = event.getX();
y = event.getY();
if (event.getAction() == MotionEvent.ACTION_MOVE) {
net.setX(x);
net.setY(y);
}
return true;
}
});
public boolean Collision(ImageView net, ImageView ball)
{
Rect BallRect = new Rect();
ball.getHitRect(BallRect);
Rect NetRect = new Rect();
net.getHitRect(NetRect);
return BallRect.intersect(NetRect);
}
}
Something like this:
boolean collision = net.getRect().intersect(ball.getRect());
Collision is a boolean
if(boolean) //Action
Then
if(collision) score.setText("INTERSECT DETECTED");
OR
public boolean Collision(ImageView a, ImageView b)
{
Rect AR = new Rect();
a.getHitRect(myViewRect);
Rect BR = new Rect();
b.getHitRect(otherViewRect1);
return Rect.intersects(AR, BR);
}
--
if(Collision(net, ball))
{
//Do action
}
--
ImageView ball = (ImageView) findViewById(R.id.Ball);
ImageView net = (ImageView) findViewById(R.id.Net);
if(Collision(net, ball))
{
//Collision detected
}
--
import android.graphics.Rect;
public boolean Collision(ImageView ball, ImageView net)
{
Rect ballRect = new Rect();
ball.getDrawingRect(ballRect);
Rect netRect = new Rect();
net.getDrawingRect(netRect);
return Rect.intersects(ballRect, netRect);
}
Check this post how to detect when a ImageView is in collision with another ImageView?

Need help onTouch Event

I am programming a little application for a school project : the concept is simple : A song is played while circle pop randomly on the screen during a brief moment and the users have to click on the screen to gain points.
I found this code for the circle which is working fine :
public class Partie extends AppCompatActivity {
RelativeLayout relativeLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SplashLaunch(this));
}
public class SplashLaunch extends View {
Handler cool = new Handler();
ObjectAnimator aa = new ObjectAnimator();
Paint newPaint = new Paint();
int randomWidthOne = 0;
int randomHeightOne = 0;
private int radiusOne = 150;
final int redColorOne = Color.RED;
final int greenColorOne = Color.GREEN;
private int lastColorOne;
private final Random theRandom = new Random();
public SplashLaunch(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
private final Runnable circleUpdater = new Runnable() {
#SuppressLint("NewApi")
#Override
public void run() {
lastColorOne = theRandom.nextInt(2) == 1 ? redColorOne : greenColorOne;
newPaint.setColor(lastColorOne);
cool.postDelayed(this, 1500); // Time between each circle to pop on the screen
int x = 0;
while (x <= 200) { // x = transparency : 0 ==> non visible , 255 ==> visible
newPaint.setAlpha(x);
x++;
}
invalidate();
}
};
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
cool.post(circleUpdater);
}
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
cool.removeCallbacks(circleUpdater);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (theRandom == null) {
randomWidthOne = (int) (theRandom.nextInt(Math.abs(getWidth() - radiusOne / 2)) + radiusOne / 2f);
randomHeightOne = (theRandom.nextInt((int) Math.abs((getHeight() - radiusOne / 2 + radiusOne / 2f))));
} else {
randomWidthOne = (int) (theRandom.nextInt(Math.abs(getWidth() - radiusOne / 2)) + radiusOne / 2f);
randomHeightOne = (theRandom.nextInt((int) Math.abs((getHeight() - radiusOne / 2 + radiusOne / 2f))));
}
} } }
So, my question is : how do I implement the onTouch event on Circle whose position constantly change ? Or do I need to think of another method like defining an invisible button at the center of the circle when he pops up ?
I found this to use the onTouch event but I don't really understand how to implement it in my case :
public boolean onTouch(View v, MotionEvent me) {
switch (me.getAction()) {
case MotionEvent.ACTION_DOWN;
x = me.getX();
y = me.getY();
}
return true;
}
I am a beginner so any help will be welcomed :).
Thanks in advance !

The onTouchEvent is not being called

I am making a game app that displays random circles all across the screen. This is all done in the onDraw method by making a never ending loop. However in the onTouchEvent method there is code that is called when a circle is clicked. The problem is when a circle is "touched" nothing happens, but sometimes something does(if you click it a lot before it disappears). Id like to know if there is a way to get the onTouch method working so these circles can be clicked.
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
public static int savedScore;
public static List<String> a = new ArrayList<String>();
public static String[] savedScores = new String[a.size()];
Paint red;
public static int howManyPoints;
public static int highestScore = 0;
boolean isTouched;
Thread newThread = new Thread();
int t = 1;
int l = 0;
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
//handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
Paint back = new Paint();
back.setColor(Color.BLACK);
Rect background = new Rect();
background.set(0, 0, canvas.getWidth(),canvas.getHeight() );
canvas.drawRect(background, back);
Paint newPaint = new Paint();
newPaint.setColor(Color.BLUE);
newPaint.setTextSize(60);
canvas.drawText("Beta v2", 10, 60, newPaint);
if(l < t){
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth , randomHeight , radius , paint);
try {
newThread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
invalidate();
}
red = new Paint();
red.setColor(Color.BLUE);
red.setTextSize(150);
canvas.drawText("" + addPoints, 500, 1350, red);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
if(lastColor == redColor){
howManyPoints = addPoints;
if(howManyPoints > highestScore){
highestScore = howManyPoints;
}
//handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
l = 1;
}
if(lastColor == greenColor){
addPoints++;
isTouched = true;
l = 0;
}
}else {
}
}
return false;
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius))){
return true;
}
return false;
}
}
You forgot to return true when you touch down
Try to add this
if(event.getAction() == MotionEvent.ACTION_DOWN){
//your code
return true;
}

How to test if something has not been touched after a circle has been drawn

I have an app that draws random circles to the screen one after another. These circles colors are also random either green or red. If you are to click a red one you loose the game if you are to click a green one you get points. What I am trying to do is add a boolean that checks if someone has not clicked on a green circle or has not clicked the screen at all when a green circle is displayed. If a red circle is displayed and the user does not click anywhere nothing happens, but in the event that a green circle is displayed and nothing is clicked the user should be redirected to another class and loose all of there points. I have tried to make a boolean called isTouched and gave it the value false then placed it all throughout my code but nothing seems to work. Here is my code if the isTouched boolean is to equal false.
if(isTouched == false){
howManyPoints = addPoints;
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
and here is the entire class.
public class DrawingView extends View{
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
public static int savedScore;
public static List<String> a = new ArrayList<String>();
public static String[] savedScores = new String[a.size()];
Paint red;
public static int howManyPoints;
boolean isTouched;
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
if(addPoints < 10){
handler.postDelayed(this, 700);
}
if(addPoints > 9 && addPoints < 30){
handler.postDelayed(this,550);
}
if(addPoints > 29){
handler.postDelayed(this, 450);
}
postInvalidate();
}
};
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
Paint back = new Paint();
back.setColor(Color.BLACK);
Rect background = new Rect();
background.set(0, 0, canvas.getWidth(),canvas.getHeight() );
canvas.drawRect(background, back);
Paint newPaint = new Paint();
newPaint.setColor(Color.BLUE);
newPaint.setTextSize(60);
canvas.drawText("ALPHA 1.64.5", 10, 60, newPaint);
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight, radius, paint);
red = new Paint();
red.setColor(Color.BLUE);
red.setTextSize(150);
canvas.drawText("" + addPoints, 500, 1350, red);
}
#SuppressWarnings("deprecation")
#Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(lastColor == redColor){
//saveScore();
howManyPoints = addPoints;
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
if(lastColor == greenColor){
addPoints++;
isTouched = true;
}
}else {
}
}
if(isTouched == false){
howManyPoints = addPoints;
handler.removeCallbacks(updateCircle);
lastColor = redColor;
addPoints = 0;
Intent i = new Intent(this.getContext(), YouFailed.class);
this.getContext().startActivity(i);
}
return false;
}
public void saveScore() {
a.add("" + addPoints);
//if(Integer.parseInt(savedScores[1]) < addPoints){
//savedScores[2] = savedScores[1];
//int x = Integer.parseInt(savedScores[1]);
//x = addPoints;
//}
}
public boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius))){
return true;
}
return false;
}
}

I get a "cannot set a static reference error" how do i set the view to an xml file

So im trying to go to an XML file called "youfailed" and for some reason i am getting an error saying that it cannot get a static reference. Is there any way to do what im trying to do?
public class DrawingView extends View {
public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
RectF rectf = new RectF(0, 0, 200, 0);
private static final int w = 100;
public static int lastColor = Color.BLACK;
private final Random random = new Random();
private final Paint paint = new Paint();
private final int radius = 230;
private final Handler handler = new Handler();
public static int redColor = Color.RED;
public static int greenColor = Color.GREEN;
int randomWidth = 0;
int randomHeight = 0;
public static int addPoints = 0;
private final Runnable updateCircle = new Runnable() {
#Override
public void run() {
lastColor = random.nextInt(2) == 1 ? redColor : greenColor;
paint.setColor(lastColor);
invalidate();
handler.postDelayed(this, 1000);
}
};
#Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
handler.post(updateCircle);
}
#Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
handler.removeCallbacks(updateCircle);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// your other stuff here
if(random == null){
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}else {
randomWidth =(int) (random.nextInt(Math.abs(getWidth()-radius/2)) + radius/2f);
randomHeight = (random.nextInt((int)Math.abs((getHeight()-radius/2 + radius/2f))));
}
canvas.drawCircle(randomWidth, randomHeight + radius/2f, radius, paint);
}
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(redColor == lastColor){
Activity.setContentView(R.layout.youfailed);
} else {
addPoints++;
}
}else {
}
return true;
}
private boolean isInsideCircle(int x, int y){
if ((((x - randomWidth)*(x - randomWidth)) + ((y - randomHeight)*(y - randomHeight))) < ((radius)*(radius)))
return true;
return false;
}
}
The error shows up in this method
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
if(isInsideCircle(x, y) == true){
//Do your things here
if(redColor == lastColor){
//it shows up right below here
Activity.setContentView(R.layout.youfailed);
} else {
addPoints++;
}
}else {
}
return true;
}
Your problem is this line:
Activity.setContentView(R.layout.youfailed);
it doesn't work this way.
You need an actual activity to set the content view. setContentView is not a static method.
UPDATE:
You seem to try to change the content of an Activity from within one of it's Child-View objects, which is very bad style and should not be done.
A View should never have control over what it's parent actually displays.
However, a callback into the parent could solve your issue.
A callback is simply an interface with one or more methods, in your case one: "onFailure()", and it would be implemented by e.g. the Activity. This "onFailure()" is called in your onTouch() instead of the setContentView(), and within your actual Activity's implementation (which has to register itself as a callback receiver just like you do with onClickListeners or onTouchListeners), you can do whatever you like.
Example for a Callback-Interface:
public interface FailureCallback {
public void onFailure();
}
You can put that as an internal interface into your DrawingView class. In your DrawingView class, you'll need a setter for the actual callback-instance and then you can call from within the onTouch() method.
In your implementation of the callback, you should not change the content of the running activity, btw - instead consider calling a new Activity using startActivity(...).

Categories