Drawing Circles using Canvas and Framelayout android - java

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.

Related

Rotating path outside onDraw Method

I'm trying to create a simple app that draws a simple figure and then after clicking the button does some affine transformation with the figure.
Can you help me finishing onClick method rotate? Thank you a lot. The problem is that I don't know how to pass Canvas to that method from onDraw method in my CanvasView, if it is possible.
MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Button button_1;
Button button_2;
Button button_3;
Button button_4;
private CanvasView customCanvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customCanvas = (CanvasView) findViewById(R.id.signature_canvas);
button_1 = (Button) findViewById(R.id.btn_1);
button_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customCanvas.translate();
}
});
button_2 = (Button) findViewById(R.id.btn_2);
button_2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customCanvas.reflect();
}
});
button_3 = (Button) findViewById(R.id.btn_3);
button_3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customCanvas.scale();
}
});
button_4 = (Button) findViewById(R.id.btn_4);
button_4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
customCanvas.rotate();//How to pass Canvas from my CanvasView to rotate method?
}
});
}
}
CanvasView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
class CanvasView extends View {
private Paint redPaint;
private Matrix matrix;
private Path path;
public CanvasView(Context c, AttributeSet attrs) {
super(c, attrs);
redPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
redPaint.setStyle(Paint.Style.STROKE);
redPaint.setColor(0xffff0000);
redPaint.setStrokeWidth(5);
matrix = new Matrix();
path = new Path();
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
path.moveTo(400, 400);
path.lineTo(400, 800);
path.lineTo(800, 700);
path.lineTo(600, 600);
path.lineTo(800, 500);
path.lineTo(400, 400);
path.close();
canvas.drawPath(path, redPaint);
}
public void translate() {
}
public void reflect() {
}
public void scale() {
}
public void rotate(Canvas canvas) {
matrix.reset();
matrix.setRotate(90, 400, 400);
path.transform(matrix);
redPaint.setColor(Color.BLUE);
canvas.drawPath(path, redPaint);
}
}
Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom">
<com.example.lab2.CanvasView
android:id="#+id/signature_canvas"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"/>
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="bottom"
android:orientation="horizontal">
<Button
android:id="#+id/btn_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Перенос"
android:textSize="8dp" />
<Button
android:id="#+id/btn_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Отражение"
android:textSize="8dp" />
<Button
android:id="#+id/btn_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Масштабирование"
android:textSize="8dp" />
<Button
android:id="#+id/btn_4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Поворот"
android:textSize="8dp" />
</LinearLayout>
</RelativeLayout>
You should not pass Canvas into rotate or any other functions. Everything related to modifying canvas should happen within onDraw method.
Update your rotate() method to invoke invalidate() method of View so it will be picked up by the system to be drawn for the next frame:
public void rotate() {
matrix.reset();
matrix.setRotate(90, 400, 400);
path.transform(matrix);
redPaint.setColor(Color.BLUE);
invalidate(); // Invalidated Views should be updated
}
Why invalidate()?
If we take a look at java docs we will find the next explanation of invalidate() method (and method body):
/**
* Invalidate the whole view. If the view is visible,
* {#link #onDraw(android.graphics.Canvas)} will be called at some point in
* the future.
* <p>
* This must be called from a UI thread. To call from a non-UI thread, call
* {#link #postInvalidate()}.
*/
public void invalidate() {
invalidate(true);
}

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 random Circles in Random Locations in Random Sizes Android

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);

How can I draw with canvas over an xml background?

I'm working on a simple project for my studies and I’m stuck with this problem.
I'm building Snakes And Ladders app and I’m trying to make my player (PNG image) to move around the board an animate.
I want the animation to happen over the game’s board background which I defined in an xml file and I just can’t do it.
The program that I will attach is not working, I have no idea why. In addition I need to add the part that takes the xml background in consideration, that part is missing and I will greatly appreciate if someone can help me solve this problem.
Thanks in advanced.
The board xml file(game.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/easymap"
android:orientation="vertical" >
<TextView
android:id="#+id/whitePlayer"
android:layout_width="32dp"
android:layout_height="32dp"
android:background="#drawable/white"
android:visibility="gone" />
<TextView
android:id="#+id/blackPlayer"
android:layout_width="32dp"
android:layout_height="32dp"
android:background="#drawable/black"
android:visibility="gone" />
<Button
android:id="#+id/btRoll"
android:layout_width="160dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignTop="#+id/cubePic"
android:background="#drawable/buttonshape"
android:text="Roll"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/cubePic"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="42dp"
android:layout_marginRight="22dp"
android:background="#drawable/cube" />
<TextView
android:id="#+id/tvTurn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/cubePic"
android:layout_alignRight="#+id/btRoll"
android:text="Your turn!"
android:textColor="#color/green"
android:textSize="32dp"
android:textStyle="italic" />
</RelativeLayout>
The java class:
package com.example.snakesnladders;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class GFX_Game extends Activity implements OnClickListener {
TextView whitePlayer, blackPlayer;
Button roll;
TextView cube, map1, map2, map3, label;
boolean yourTurn = true;
MyBringBack ourView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ourView = new MyBringBack(this);
setContentView(ourView);
init();
}
private void init() {
cube = (TextView) findViewById(R.id.cubePic);
roll = (Button) findViewById(R.id.btRoll);
label = (TextView) findViewById(R.id.tvTurn);
roll.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onClick(View view) {
int rand = (int) (Math.random() * 6) + 1;
}
class MyBringBack extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
Bitmap backGround, playerB, playerW;
boolean isRunning = true;
public MyBringBack(Context context) {
super(context);
playerW = BitmapFactory.decodeResource(getResources(),
R.id.whitePlayer);
ourHolder = getHolder();
ourThread = new Thread(this);
ourThread.start();
}
#Override
public void run() {
while (isRunning) {
if (!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawBitmap(playerW, 0, 0, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
}
The changed inner class:( I've extended View an override the onDraw method from the Viev class, and it still not working)
In addition I wanted to draw on my existing xml layout that i created in the game.xml file.
class MyBringBack extends View {
Bitmap playerW;
public MyBringBack(Context context) {
super(context);
playerW = BitmapFactory.decodeResource(getResources(),
R.id.whitePlayer);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawBitmap(playerW,0,0,null);
}
}
Create a custom View as follows. If you're root view is RelativeLayout and you need to draw on it, extend a RelativeLayout
public final class MyRelativeLayout extends RelativeLayout {
Bitmap playerW;
public MyRelativeLayout(Context context) {
super(context);
init(context);
}
public MyRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyRelativeLayout(Context context, AttributeSet attrs, int style) {
super(context, atts, style);
init(context);
}
private void init(final Context context) {
playerW = BitmapFactory.decodeResource(context.getResources(),
R.id.whitePlayer);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(playerW,0,0,null);
}
}
Then use it in xml as follows
<?xml version="1.0" encoding="utf-8"?>
<your.package.name.package.MyRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
all the stuff here
<your.package.name.package.MyRelativeLayout>

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