Drawing random Circles in Random Locations in Random Sizes Android - java

I have made a lot of progress on this assignment. The final product needs to add a circle in a random color/random size/random location after each click of a button(circle). I have another button(clear) that needs to clear the canvas. Here are the two problems i'm facing now. My circles are not being displayed in random locations. They all start from the top left of the screen. Second problem is that i have no idea how to get my clear button working. Everything else is working, random circles colors in random circle sizes.
package com.example.randomcircles;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
public class DisplayRandomCircles extends Activity
{
FrameLayout f1;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_display_random_circles);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
f1 = (FrameLayout) findViewById(R.id.frame);
}
#SuppressLint("WrongCall")
public void doit(View v)
{
int rand = (int) (Math.random() * 60);
switch (v.getId())
{
case (R.id.btn1):
DrawCircle c = new DrawCircle(getApplicationContext());
f1.addView(c);
break;
case (R.id.btn2):
DrawCircle d = new DrawCircle(getApplicationContext());
f1.addView(d);
break;
}
}
}
package com.example.randomcircles;
import java.util.Random;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawCircle extends View
{
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
public DrawCircle(Context con)
{
super(con);
}
#SuppressLint("DrawAllocation")
#Override
public void onDraw(Canvas c)
{
super.onDraw(c);
int color = Color.rgb(red, green, blue);
int rand = (int)(Math.random() * 200);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setAntiAlias(true);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(100);
p.setColor(color);
p.setStyle(Paint.Style.FILL);
c.drawCircle(rand, rand, rand, p);
clear(c);
}
public void clear(Canvas c)
{
c.drawColor(Color.TRANSPARENT);
}
public void drawColor(int transparent) {
// TODO Auto-generated method stub
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="bottom|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom"
android:layout_weight=".50"
android:onClick="doit"
android:text="#string/Circle" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:layout_gravity="end|bottom"
android:onClick="doit"
android:text="#string/Clear" />
</LinearLayout>
</LinearLayout>

Your random function is not effective to draw circles on the current view (most likely because you have high resolution device) you have to get with and height of the view to draw your circle on it randomly.
int minRadius = 100;
Random random = new Random();//define this outside you onDraw fucntion
int w = getWidth();
int h = getHeight();
int randX = random.nextInt(w);
int randY = random.nextInt(h);
int randR = minRadius + random.nextInt(100);
...
c.drawCircle(randX, randY, randR, p);
also reset you view by drawing color on you whole canvas
canvas.drawColor(Color.WHITLE);

Related

Create a clear button to clear canvas android

I can't get my clear button to work in my program. My circle button works which displays random circles but my clear button does nothing. I'm lost. I know i'm supposed to use drawColor.Color.TRANSPARENT or the mode.clear but nothing is working.
package com.example.randomcircles;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.content.*;
public class DisplayRandomCircles extends Activity
{
FrameLayout f1, f2;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_display_random_circles);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
f1 = (FrameLayout) findViewById(R.id.frame);
}
#SuppressLint("WrongCall")
public void doit(View v)
{
int rand = (int) (Math.random() * 60);
DrawCircle c = new DrawCircle(getApplicationContext());
Canvas d = new Canvas();
Paint p = new Paint();
switch (v.getId())
{
case (R.id.btn1):
f1.addView(c);
break;
case (R.id.btn2):
d.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
break;
}
}
}
package com.example.randomcircles;
import java.util.Random;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.*;
import android.view.*;
public class DrawCircle extends View
{
Random random = new Random();
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
int randX = random.nextInt(700);
int randY = random.nextInt(1000);
int randR = random.nextInt(200);
int color = Color.rgb(red, green, blue);
public DrawCircle(Context con)
{
super(con);
}
#SuppressLint("DrawAllocation")
#Override
public void onDraw(Canvas c)
{
super.onDraw(c);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setAntiAlias(true);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(100);
p.setColor(color);
p.setStyle(Paint.Style.FILL);
c.drawCircle(randX, randY, randR, p);
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="bottom|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom"
android:layout_weight=".50"
android:onClick="doit"
android:text="#string/Circle" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:layout_gravity="end|bottom"
android:onClick="doit"
android:text="#string/Clear" />
</LinearLayout>
</LinearLayout>
You are creating a new instance of DrawCircle every time doIt is called.
The old instance is still there. So you need to either remove the old view from f1, or get the exact same instance of DrawCircle you created before, set the new color, and then call invalidate() on the DrawCircle to force the redraw.

Drawing Circles using Canvas and Framelayout android

I am trying to create an app that displays a circle everytime I click a button. I have the layout looking great but when i click the button(circle) to display a circle on the screen nothing happens. I'm not confident that my draw circle class is being called correctly in my main activity. Here is my code below.
package com.example.randomcircles;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class DisplayRandomCircles extends Activity
{
DrawCircle c;
Canvas d;
#Override
public void onCreate(Bundle b)
{
super.onCreate(b);
setContentView(R.layout.activity_display_random_circles);
Button btn1 = (Button) findViewById(R.id.btn1);
Button btn2 = (Button) findViewById(R.id.btn2);
c = new DrawCircle(getApplicationContext());
d = new Canvas();
FrameLayout f1 = (FrameLayout) findViewById(R.id.frame);
}
#SuppressLint("WrongCall")
public void doit(View v)
{
switch (v.getId())
{
case (R.id.btn1):
c.onDraw(d);
break;
case (R.id.btn2):
break;
}
}
}
Here is my DrawCircle class
package com.example.randomcircles;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawCircle extends View
{
public DrawCircle(Context con)
{
super(con);
}
#Override
protected void onDraw(Canvas c)
{
super.onDraw(c);
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
p.setAntiAlias(true);
p.setStyle(Paint.Style.STROKE);
p.setStrokeWidth(100);
p.setColor(Color.RED);
p.setStyle(Paint.Style.FILL);
c.drawCircle(75, 75, 100, p);
}
}
And my layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:gravity="bottom|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start|bottom"
android:layout_weight=".50"
android:onClick="doit"
android:text="#string/Circle" />
<Button
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight=".50"
android:layout_gravity="end|bottom"
android:onClick="doit"
android:text="#string/Clear" />
</LinearLayout>
</LinearLayout>
Ok, here are some changes I'd make for this. I'm not exactly sure what you're trying to do, but this should make things easier.
First, change your class "DrawCircle" like this:
public class DrawCircle extends View
{
final Paint circlePaint;
{
circlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
circlePaint.setAntiAlias(true);
circlePaint.setStyle(Paint.Style.STROKE);
circlePaint.setStrokeWidth(100);
circlePaint.setColor(Color.RED);
circlePaint.setStyle(Paint.Style.FILL);
}
public DrawCircle(Context con)
{
super(con);
}
public DrawCircle(Context con, AttributeSet set)
{
super(con, set);
}
public DrawCircle(Context con, AttributeSet set, int style)
{
super(con, set, style);
}
#Override
protected void onDraw(Canvas c)
{
super.onDraw(c);
c.drawCircle(75, 75, 100, circlePaint);
}
}
This will allow you to reuse the same Paint object with each draw because the onDraw() method can be called hundreds of times and there's no need to slow down your program for this.
Second, adding the other constructors allows you to add the View to your FrameLayouts by xml.
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.randomCircles.DrawCircle
android:id="#+id/circleFrame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Next, to fill your screen, you need to loop in your onDraw method. Think about drawing on the canvas as a stamp. Every time you draw, you stamp your image at the location you specify on top of the previous draw.
So
protected void onDraw(Canvas c)
{
super.onDraw(c);
for(int i = 0; i < 10; i++)
{
c.drawCircle(i*100, 75, 100, circlePaint);
}
}
This should draw 10 circles of radius 100 pixels across the top of your screen.

How to change drawLine color on an Activity

I have the following TestView class:
package com.example.tview;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
public class TestView extends Activity {
FrameLayout layout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_view);
layout = (FrameLayout)findViewById(R.id.viewd);
//layout.removeAllViews();
CustomView view = new CustomView(TestView.this);
view.setText("A");
view.setGravity(Gravity.CENTER);
view.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/led.ttf"));
view.setTextSize(400);
view.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
layout.addView(view);
}
}
CustomView class:
package com.example.tview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Style;
import android.view.MotionEvent;
import android.widget.TextView;
public class CustomView extends TextView {
Paint paint;
Path path;
float x = 0;
float y = 0;
private int cYellow = Color.YELLOW;
private int[] theColors = {Color.YELLOW, Color.BLUE, Color.GREEN, Color.BLACK, Color.RED, Color.CYAN, Color.DKGRAY, Color.WHITE, Color.BLACK, Color.MAGENTA};
public CustomView(Context context) {
super(context);
paint = new Paint();
path= new Path();
paint.setAlpha(255);
paint.setColor(cYellow);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(20);
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPath(path,paint);
canvas.drawCircle(x, y, 10, paint);
}
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
path.moveTo(event.getX(), event.getY());
path.lineTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_MOVE:
x = event.getX();
y = event.getY();
path.lineTo(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
path.lineTo(event.getX(), event.getY());
break;
case MotionEvent.ACTION_CANCEL:
break;
default:
break;
}
return true;
}
}
My XML layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#000000"
android:layout_gravity="center" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YELLOW" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GREEN" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:orientation="vertical"
android:background="#ffffff"
android:layout_gravity="center" >
<FrameLayout
android:id="#+id/viewd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bd"
android:orientation="vertical" >
</FrameLayout>
</LinearLayout>
</LinearLayout>
I have the Color array setup in my CustomView class, How can I set the stroke color at runtime?
So by default it should be Color.YELLOW but if I press the Green button the stroke color should be Color.GREEN
TestView class UPDATE (working):
package com.example.tview;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
public class TestView extends Activity {
FrameLayout layout;
Paint paint;
public int paintColor = Color.GREEN;
CustomView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_view);
layout = (FrameLayout)findViewById(R.id.viewd);
//layout.removeAllViews();
view = new CustomView(TestView.this);
view.setText("A");
view.setGravity(Gravity.CENTER);
view.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/led.ttf"));
view.setTextSize(400);
view.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
layout.addView(view);
Button btn2 = (Button) findViewById(R.id.button2);
btn2.setOnClickListener(eHandle);
}
View.OnClickListener eHandle = new View.OnClickListener() {
public void onClick(View v) {
view.paint.setColor(paintColor);
}
};
}
You have defined a paint using whihc you draw on the canvas. On button press set the appropriate color to to your paint:
paint.setColor(Color);
Set proper color to this line everytme you press button

Animation on Android

I have been looking around and searching for an answer and really trying to dive into android programming before asking any questions. I know that this site is here to help, but also not an outlet to be redundant and lazy. Though I am a begginer with android and am in need of some assistance if some of you have the time. I looked at a question that I really thought would help (URL: Button animations in android) But it just ended up making my program crash. I also checked out this one http://mobile.tutsplus.com/tutorials/android/android-sdk-creating-a-simple-property-animation/ , which also didn't really get me to the correct answer I was looking for. Now I have no code unfortunately but have tried to replicate the code from both of these example sites I have provided. They both crash when I get to the declaration of animation objects in the actual java code
i.e.
ImageView confettiStart = (ImageView) findViewById(R.id.confetti);
AnimatorSet confettiSet =(AnimatorSet)AnimatorInflater.loadAnimator(this,R.animator.startconfettianimations);
My goal is to basically just have a confetti animation come from the top of my screen and roll down to the bottom of my screen. I have created about 8 different images in order to create an "animation" but I really do not know how to implement this in Android itself. If someone could help or point me in the right direction I would greatly appreciate it. Thank you so much.
Use objectAnimator for that view and in that keep x parameter same while Change y parameter to 0 to 600 or something same . Hope it works. or translator animator will do the trick try it keep x1=0 x2=0 and y1=0 y2=600.
package com.shubh;
import android.os.Build;
import android.os.Bundle;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_main);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
public void startAnimation(View view) {
float dest = 0;
ImageView aniView = (ImageView) findViewById(R.id.imageView1);
switch (view.getId()) {
case R.id.Button01:
dest = 360;
if (aniView.getRotation() == 360) {
System.out.println(aniView.getAlpha());
dest = 0;
}
ObjectAnimator animation1 = ObjectAnimator.ofFloat(aniView,
"rotation", dest);
animation1.setDuration(2000);
animation1.start();
// Show how to load an animation from XML
// Animation animation1 = AnimationUtils.loadAnimation(this,
// R.anim.myanimation);
// animation1.setAnimationListener(this);
// animatedView1.startAnimation(animation1);
break;
case R.id.Button02:
// Shows how to define a animation via code
// Also use an Interpolator (BounceInterpolator)
Paint paint = new Paint();
TextView aniTextView = (TextView) findViewById(R.id.textView1);
float measureTextCenter = paint.measureText(aniTextView.getText()
.toString());
dest = 0 - measureTextCenter;
if (aniTextView.getX() < 0) {
dest = 0;
}
ObjectAnimator animation2 = ObjectAnimator.ofFloat(aniTextView,
"x", dest);
animation2.setDuration(2000);
animation2.start();
break;
case R.id.Button03:
// Demonstrate fading and adding an AnimationListener
RelativeLayout mainContainer = (RelativeLayout) findViewById(R.id.layout);
LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(this, R.anim.main_layout_animation);
mainContainer.setLayoutAnimation(controller);
dest = 1;
Button button3=(Button)findViewById(R.id.Button03);
button3.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.hyperspace_jump));
if (aniView.getAlpha() > 0) {
dest = 0;
}
ObjectAnimator animation3 = ObjectAnimator.ofFloat(aniView,
"alpha", dest);
animation3.setDuration(2000);
animation3.start();
break;
case R.id.Button04:
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(aniView, "alpha",
0f);
fadeOut.setDuration(2000);
ObjectAnimator mover = ObjectAnimator.ofFloat(aniView,
"translationX", -500f, 0f);
mover.setDuration(2000);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(aniView, "alpha",
0f, 1f);
fadeIn.setDuration(2000);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(mover).with(fadeIn).after(fadeOut);
animatorSet.start();
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, HitActivity.class);
startActivity(intent);
return true;
}
}
and the xml is
<?xml version="1.0" encoding="utf-8" ?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
- <LinearLayout android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:id="#+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Rotate" />
<Button android:id="#+id/Button04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Group" />
<Button android:id="#+id/Button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Fade" />
<Button android:id="#+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAnimation"
android:text="Animate" />
</LinearLayout>
<ImageView android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/img" />
<TextView android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/imageView1"
android:layout_alignRight="#+id/imageView1"
android:layout_marginBottom="30dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Try this
public class HitActivity extends Activity {
private ObjectAnimator animation1;
private ObjectAnimator animation2;
private Button button;
private Random randon;
private int width;
private int height;
private AnimatorSet set;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_chemist_list);
width = getWindowManager().getDefaultDisplay().getWidth();
height = getWindowManager().getDefaultDisplay().getHeight();
randon = new Random();
set = createAnimation();
set.start();
set.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
int nextX = randon.nextInt(width);
int nextY = randon.nextInt(height);
animation1 = ObjectAnimator.ofFloat(button, "x", button.getX(),
nextX);
animation1.setDuration(1400);
animation2 = ObjectAnimator.ofFloat(button, "y", button.getY(),
nextY);
animation2.setDuration(1400);
set.playTogether(animation1, animation2);
set.start();
}
});
}
public void onClick(View view) {
String string = button.getText().toString();
int hitTarget = Integer.valueOf(string) + 1;
button.setText(String.valueOf(hitTarget));
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
private AnimatorSet createAnimation() {
int nextX = randon.nextInt(width);
int nextY = randon.nextInt(height);
button = (Button) findViewById(R.id.Button01);
animation1 = ObjectAnimator.ofFloat(button, "x", nextX);
animation1.setDuration(1400);
animation2 = ObjectAnimator.ofFloat(button, "y", nextY);
animation2.setDuration(1400);
AnimatorSet set = new AnimatorSet();
set.playTogether(animation1, animation2);
return set;
}
}

NullPointerException with view.getLocationOnScreen

Very new to Android and have researched this for a while now but can't quite find the answer. I'm sure there's a simple solution.
I'm getting a NullPointException which is connected to my View characterContainer = findViewById(R.id.icon_container);
As I understand it, it seems I'm trying to implement it in the onCreate() method and as such the layout is not fully ready yet causing characterContainer = null.
So I need to use it in onStart() or onResume() but I'm struggling. This is my code so far:
package harvest.life.game;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class HarvestLifeActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//find buttons on screen
Button up = (Button)findViewById(R.id.up);
up.setOnTouchListener(new UpListener());
Button down = (Button)findViewById(R.id.down);
down.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons
Button left = (Button)findViewById(R.id.left);
left.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons
Button right = (Button)findViewById(R.id.right);
right.setOnTouchListener(new UpListener()); // set as UpListener also for test reasons
}
//what up button does
private final class UpListener implements OnTouchListener {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//as long as up button is pressed it will keep moving character up
while (event.getAction() == MotionEvent.ACTION_DOWN)
{
View characterContainer = findViewById(R.id.icon_container);
Drawable walking = getResources().getDrawable(R.drawable.test_circle_red);
int startX = characterContainer.getLeft();
int startY = characterContainer.getTop();
int defaultWidth = characterContainer.getWidth();
int defaultHeight = characterContainer.getHeight();
//create new position for character 1 pixel closer to the top of screen
int newX = startX - 1;
int newY = startY;
//remove character
RelativeLayout view = (RelativeLayout) characterContainer;
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
//re make character in new position created above and assign background as walking forwards animation
RelativeLayout.LayoutParams characParams = new RelativeLayout.LayoutParams(defaultWidth,defaultHeight);
characParams.leftMargin = newY;
characParams.topMargin = newX;
characterContainer.setLayoutParams(characParams);
characterContainer.setBackgroundDrawable(walking);
}
break;
// when button is let go of
case MotionEvent.ACTION_UP:
RelativeLayout characterContainer = (RelativeLayout)
findViewById(R.id.icon_container);
Drawable standing =
getResources().getDrawable(R.drawable.test_circle);
//assign background back to standing animation
characterContainer.setBackgroundDrawable(standing);
default:
break;
}
return true;
}
}
public void onResume() { // what goes here?
}
}
Do I need to put a sort of function call in the onResume section or do I put the code for what the OnTouchListener does in here?
here's my main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/game_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#FFFFFF">
<RelativeLayout
android:id="#+id/side_bar_right"
android:layout_width="50dp"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#000000">
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/up"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="top"
android:src="#drawable/up" />
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/down"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/down" />
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/right"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/right" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/side_bar_left"
android:layout_width="50dp"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#000000">
<ImageView
android:contentDescription="#string/movement_button"
android:id="#+id/left"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#drawable/left" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/icon_container"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#drawable/test_circle" >
</RelativeLayout >
</RelativeLayout>
Here's what I think you wanted:
package harvest.life.game;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
public class HarvestLifeActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//find buttons on screen
Button up = (Button)findViewById(R.id.up);
//up.setOnTouchListener(new UpListener());
Button down = (Button)findViewById(R.id.up);
//down.setOnTouchListener(new UpListener());
Button left = (Button)findViewById(R.id.up);
//left.setOnTouchListener(new UpListener());
Button right = (Button)findViewById(R.id.up);
//right.setOnTouchListener(new UpListener());
}
public void onDownButtonClick(View view){
while (event.getAction() == MotionEvent.ACTION_DOWN)
{
View characterContainer = findViewById(R.id.icon_container);
Drawable walking = getResources().getDrawable(R.drawable.test_circle_red);
int startX = characterContainer.getLeft();
int startY = characterContainer.getTop();
int defaultWidth = characterContainer.getWidth();
int defaultHeight = characterContainer.getHeight();
//create new position for character 1 pixel closer to the top of screen
int newX = startX - 1;
int newY = startY;
//remove character
RelativeLayout view = (RelativeLayout) characterContainer;
ViewGroup owner = (ViewGroup) view.getParent();
owner.removeView(view);
//re make character in new position created above and assign background as walking forwards animation
RelativeLayout.LayoutParams characParams = new RelativeLayout.LayoutParams(defaultWidth,defaultHeight);
characParams.leftMargin = newY;
characParams.topMargin = newX;
characterContainer.setLayoutParams(characParams);
characterContainer.setBackgroundDrawable(walking);
}
}
public void onUpButtonClicked(View view){
RelativeLayout characterContainer = (RelativeLayout)
findViewById(R.id.icon_container);
Drawable standing =
getResources().getDrawable(R.drawable.test_circle);
//assign background back to standing animation
characterContainer.setBackgroundDrawable(standing);
}
}
As you can see, I put your 'down' code in a function, and your 'up' code in another function. Then, in the xml, add android:onClick="onButtonDownClick" to the down button. Do the same (except with an 'onButtonUpClick') to your up button. This will cause those functions to be called on click. It's important to note that those functions take a View as an argument.

Categories

Resources