android - for loop drawing circles not working? - android

I am trying to draw multiple circles from an array and it is throwing a "force close" when I try to run the code. Any ideas here?
package com.adam.PlaySound;
import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class ButtonPress extends Activity {
/** Called when the activity is first created. */
int numPlayers = 3;
boolean toggle = true;
LinearLayout parent;
Button button;
TextView text;
TextView text2;
DisplayMetrics dm = new DisplayMetrics();
MediaPlayer mediaPlayer[] = new MediaPlayer[numPlayers];
//this array is a placeholder for the loops in a cluster
//essentially this array will be populated through a database
//based on which cluster someone is within
//and the region arrays will be populated by the same database
String soundFiles[] = {"drums_1.mp3", "lead.mp3", "strings.mp3"};
public LoopRegion region[] = new LoopRegion[numPlayers];
float regionX[] = {20, 80, 150};
float regionY[] = {20, 200, 350};
int regionR[] = {50, 80, 100};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setContentView(R.id.view1);
parent = (LinearLayout) findViewById(R.id.parent);
button = (Button) findViewById(R.id.button1);
text = (TextView) findViewById(R.id.text);
text2 = (TextView) findViewById(R.id.text2);
parent.setOnTouchListener(Motion);
button.setOnClickListener(on_off);
for (int i = 0; i < numPlayers; i++){
String path = "http://soundclusters.adamlaskowitz.com/uploads/" + soundFiles[i];
mediaPlayer[i] = new MediaPlayer();
//mediaPlayer[i] = MediaPlayer.create(ButtonPress.this, R.raw.drums_2);
mediaPlayer[i] = MediaPlayer.create(ButtonPress.this, Uri.parse(path));
mediaPlayer[i].setLooping(true);
}
for (int i = 0; i < numPlayers; i++){
region[i] = new LoopRegion(this,regionX[i],regionY[i],regionR[i]);
parent.addView(region[i]);
}
getWindowManager().getDefaultDisplay().getMetrics(dm);
}
This is the LoopRegion class.
package com.adam.PlaySound;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
/*This class will create a circle region for
*each loop within a cluster */
public class LoopRegion extends View {
private float x;
private float y;
private int r;
private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
public LoopRegion(Context context, float x, float y, int r) {
super(context);
mPaint.setColor(0xFFFF0000);
this.x = x;
this.y = y;
this.r = r;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, mPaint);
}
public void setCoordinate(float mx, float my){
this.x = mx;
this.y = my;
//this.r = 300;
}
}
And this is the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/parent"
>
<TextView android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Not Playing"
/>
<TextView android:id="#+id/text2"
android:layout_height="wrap_content"
android:text="Location" android:layout_width="wrap_content"
/>
<Button android:text="Sound On/Off"
android:id="#+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>
<!-- <View android:id="#+id/view1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</View>-->
</LinearLayout>
Thanks in advance!

My guess is that your LoopRegion views have layout parameters set to FILL_PARENT and the first one pushes the others off the screen. It would help to see the code for how a LoopRegion is created, and perhaps the XML for the parent LinearLayout.

Related

Surface View and Linear layout and onClick event

I have a problem with adding my surface view to a linear layout, I have tried the already available answers and still cant seem to figure it out. My aim is to render an animation at the bottom of my login screen when my the next button is clicked. I tried adding a linear Layout to the Screen and then adding my gameView object on to that.
This is the loginActivity and game View Class for clarity I've also added the xml.
`package com.example.Combat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.*;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
public GameView gameView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setting the font
Typeface myTypeFace = Typeface.createFromAsset(getAssets(),"Typo Oxin free promo.ttf");
TextView myTextView = (TextView) findViewById(R.id.nameTextView);
myTextView.setTypeface(myTypeFace);
gameView = new GameView(this);
// LinearLayout.LayoutParams lp =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// lp.gravity= Gravity.BOTTOM;
LinearLayout myLayout = new LinearLayout(this);
myLayout.findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);
}
#Override
public void onResume(){
super.onResume();
gameView.resume();
}
#Override
protected void onPause(){
super.onPause();
gameView.pause();
}
public void beginMotion(View view) {
GameView.isMoving=!GameView.isMoving;
// startActivity(new Intent(getApplicationContext(),transitionActivity.class));
}
}
`
package com.example.Combat;
import android.content.Context;
import android.graphics.*;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Created by vmuser on 2017/05/05.
*/
public class GameView extends SurfaceView implements Runnable{
private Thread gameThread;
private SurfaceHolder ourHolder;
public static volatile boolean playing=false;
private Canvas canvas;
private Bitmap bitmapRunningMan;
public static boolean isMoving=false;
private float runSpeedPerSecond = 150;
//LinearLayout screen=(LinearLayout)findViewById(R.id.theScreen);
private float manXPos = 1020, manYPos = 950;
private int frameWidth = 230, frameHeight = 274;
private int frameCount = 6;
private int currentFrame = 0;
private long fps;
private long timeThisFrame;
private long lastFrameChangeTime = 0;
private int frameLengthInMillisecond = 60;
private Rect frameToDraw = new Rect(0, 0, frameWidth, frameHeight);
private RectF whereToDraw = new RectF(manXPos, manYPos, manXPos + frameWidth, frameHeight);
public GameView(Context context) {
super(context);
ourHolder = getHolder();
bitmapRunningMan = BitmapFactory.decodeResource(getResources(),
R.drawable.perfectsoldier);
bitmapRunningMan = Bitmap.createScaledBitmap(bitmapRunningMan,
frameWidth * frameCount, frameHeight, false);
}
#Override
public void run() {
while (playing) {
long startFrameTime = System.currentTimeMillis();
update();
this.draw();
Log.d("theOne","its Happennig");
timeThisFrame = System.currentTimeMillis() - startFrameTime;
if (timeThisFrame >= 1) {
fps = 1000 / timeThisFrame;
}
}
}
public void update() {
if (isMoving) {
manXPos = manXPos - runSpeedPerSecond / fps;
if (manXPos > 0) {
//manYPos += (int) frameHeight;
//manXPos = 10;
isMoving=false;
}
if (manYPos + frameHeight > 0) {
// manYPos = 10;
isMoving=false;
}
}
}
public void manageCurrentFrame() {
long time = System.currentTimeMillis();
if (isMoving) {
if (time > lastFrameChangeTime + frameLengthInMillisecond) {
lastFrameChangeTime = time;
currentFrame++;
if (currentFrame >= frameCount) {
currentFrame = 0;
}
}
}
frameToDraw.left = currentFrame * frameWidth;
frameToDraw.right = frameToDraw.left + frameWidth;
}
public void draw() {
if (ourHolder.getSurface().isValid()) {
canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
whereToDraw.set((int) manXPos, (int) manYPos, (int) manXPos
+ frameWidth, (int) manYPos + frameHeight);
manageCurrentFrame();
canvas.drawBitmap(bitmapRunningMan, frameToDraw, whereToDraw, null);
ourHolder.unlockCanvasAndPost(canvas);
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch(InterruptedException e) {
Log.e("ERR", "Joining Thread");
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
// public boolean onTouchEvent(MotionEvent event) {
// switch (event.getActionMasked() & MotionEvent.ACTION_MASK) {
// case MotionEvent.ACTION_DOWN :
// isMoving = !isMoving;
// break;
// }
//
// return true;
// }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusableInTouchMode="true"
android:color="#000000"
android:weightSum="1" android:background="#ffffff" android:orientation="vertical"
android:id="#+id/theScreen">
<ImageView
android:layout_width="113dp"
android:layout_height="130dp"
android:src="#drawable/thelogo"
android:id="#+id/imageView" android:layout_gravity="center_horizontal"/>
<TextView
android:layout_width="145dp"
android:layout_height="49dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="combat"
android:textSize="30sp"
android:textColor="#000000"
android:id="#+id/nameTextView" android:layout_gravity="right" android:layout_weight="0.06"/>
<EditText
android:layout_width="270dp"
android:layout_height="wrap_content"
android:hint="Username"
android:textColorHint="#808080"
android:textColor="#22272a"
android:id="#+id/userNameEditText" android:layout_gravity="center_horizontal"/>
<Button
android:layout_width="261dp"
android:layout_height="wrap_content"
android:text="Next"
android:drawableRight="#drawable/thearrow"
android:textColor="#000000"
android:onClick="beginMotion"
android:id="#+id/NextButton" android:layout_gravity="center_horizontal" android:background="#638455"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Create an account"
android:id="#+id/textView" android:layout_gravity="center_horizontal" android:layout_weight="0.07"
android:textColor="#22272A"/>
<LinearLayout
android:id="#+id/gameLayoutView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
</LinearLayout>
</LinearLayout>
You haven't attached myLayout to the activity main layout that you earlier set on setContentView(R.layout.main).
Instead of:
LinearLayout myLayout = new LinearLayout(this);
myLayout.findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);
You should write this:
LinearLayout myLayout = (LinearLayout) findViewById(R.id.gameLayoutView);
myLayout.addView(gameView);

How to put Circle class into layout

I want to put Circle class into my layout. I tried it but app got stopped on creating. I think the problem is in xml code in the first line which is under. Kindly guide me.
<com.package.Circle
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/circle"
android:layout_width="300dp"
android:layout_height="300dp" />
XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.zohaib.animatedcircle.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<com.package.Circle
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/circle"
android:layout_width="300dp"
android:layout_height="300dp" />
</RelativeLayout>
Circle.java
package com.example.zohaib.animatedcircle;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
public class Circle extends View {
private static final int START_ANGLE_POINT = 90;
private final Paint paint;
private final RectF rect;
private float angle;
public Circle(Context context, AttributeSet attrs) {
super(context, attrs);
final int strokeWidth = 40;
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(strokeWidth);
//Circle color
paint.setColor(Color.RED);
//size 200x200 example
rect = new RectF(strokeWidth, strokeWidth, 200 + strokeWidth, 200 + strokeWidth);
//Initial Angle (optional, it can be zero)
angle = 120;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawArc(rect, START_ANGLE_POINT, angle, false, paint);
}
public float getAngle() {
return angle;
}
public void setAngle(float angle) {
this.angle = angle;
}
}
MainActivity.java
package com.example.zohaib.animatedcircle;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Circle circle = (Circle) findViewById(R.id.circle);
CircleAngleAnimation animation = new CircleAngleAnimation(circle, 240);
animation.setDuration(1000);
circle.startAnimation(animation);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The XML element name needs to be the fully qualified class name of your custom View class. In this case, it would be com.example.zohaib.animatedcircle.Circle, instead of com.package.Circle.
<com.example.zohaib.animatedcircle.Circle
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/circle"
android:layout_width="300dp"
android:layout_height="300dp" />

Couldn't click on buttons when child view is added?

When I use child view then the buttons which are in the root view are disabled. I could not click on them.
I am trying to develop application in which input is made by connecting buttons with lines. If user wants to enter
some thing then he have to touch buttons by connecting them with lines. It is very similar to android pattern
unlock. But in our application in place of dots of grid, numbers will be shown.
activity_demo_main:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".DemoMainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<Button
android:id="#+id/button1"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="222.08203dp"
android:layout_marginTop="270.53426dp"
android:text="1" />
<Button
android:id="#+id/button2"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="162.08203dp"
android:layout_marginTop="314.12678dp"
android:text="2" />
<Button
android:id="#+id/button3"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="87.917960dp"
android:layout_marginTop="314.12678dp"
android:text="3" />
<Button
android:id="#+id/button4"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="27.917960dp"
android:layout_marginTop="270.53423dp"
android:text="4" />
</RelativeLayout>
DemoMainActivity.java :
package com.example.demo;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
public class DemoMainActivity extends Activity {
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_main);
rl = (RelativeLayout)findViewById(R.id.rty);
Button b1=(Button)findViewById(R.id.button2);
final NewPattern b = new NewPattern(this);
b1.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View arg0) {
try{
rl.getRootView();
rl.addView(b);
}
catch(Exception ex){}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.demo_main, menu);
return true;
}
}
NewPattern.java:
package com.example.demo;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
//import com.example.newpattern.PatternMainActivity;
import android.widget.RelativeLayout;
public class NewPattern extends View
{
private Paint m_paint;
private static Bitmap m_bitmap;
private Canvas m_canvas;
private Path m_path;
private Paint m_bitmapPaint;
private DisplayMetrics m_metrics;
private int m_color = 0xFFFF0000;
static boolean m_pathDrawn = false;
private float m_X, m_Y;
private static final float TOUCH_TOLERANCE = 4;
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
RelativeLayout rl = (RelativeLayout)findViewById(R.id.rty);
#SuppressLint("NewApi")
private void touchman(float g, float h){
final float btn1x = b1.getX();
//float btn2x= b1.getY();
if(g==btn1x){
rl.getRootView();
}
}
public NewPattern(Context context, AttributeSet attrs) {
super(context, attrs);
//Your code
// btn1.setText("fdsf");
}
public NewPattern(Context p_c)
{
super(p_c);
try{
m_paint = new Paint();
m_paint.setAntiAlias(true);
m_paint.setDither(true);
m_paint.setColor(m_color);
/*new ColorPickerDialog(p_c, new OnColorChangedListener()
{
public void colorChanged(int p_color)
{
m_paint.setColor(p_color);
m_color = p_color;
}
}, 0xFFFF0000).show();*/
m_paint.setStyle(Paint.Style.STROKE);
m_paint.setStrokeJoin(Paint.Join.ROUND);
m_paint.setStrokeCap(Paint.Cap.ROUND);
m_paint.setStrokeWidth(12);
m_metrics = p_c.getResources().getDisplayMetrics();
m_bitmap =
Bitmap.createBitmap(m_metrics.widthPixels, m_metrics.heightPixels,
Bitmap.Config.ARGB_8888);
m_canvas = new Canvas(m_bitmap);
m_path = new Path();
m_bitmapPaint = new Paint(Paint.DITHER_FLAG);
}
catch(Exception ex){}}
public void onerase()
{
m_canvas = null;
}
#Override
protected void onSizeChanged(int p_w, int p_h, int p_oldw, int p_oldh)
{
super.onSizeChanged(p_w, p_h, p_oldw, p_oldh);
}
#Override
protected void onDraw(Canvas p_canvas)
{try{
p_canvas.drawColor(0x00000000);
p_canvas.drawBitmap(m_bitmap, 0, 0, m_bitmapPaint);
p_canvas.drawPath(m_path, m_paint);}
catch(Exception ex){}
}
#SuppressLint("NewApi")
private void touch_start(float p_x, float p_y)
{//try{
m_path.reset();
m_path.moveTo(p_x, p_y);
m_X = p_x;
m_Y = p_y;
//}
//catch(Exception ex){}
}
private void touch_move(float p_x, float p_y)
{try{
float m_dx = Math.abs(p_x - m_X);
float m_dy = Math.abs(p_y - m_Y);
if (m_dx >= TOUCH_TOLERANCE || m_dy >= TOUCH_TOLERANCE)
{
m_path.quadTo(m_X, m_Y, (p_x + m_X) / 2, (p_y + m_Y) / 2);
m_X = p_x;
m_Y = p_y;
m_pathDrawn = true;
}}
catch(Exception ex){}
}
private void touch_up()
{try{
m_path.lineTo(m_X, m_Y);
// commit the path to our offscreen
m_canvas.drawPath(m_path, m_paint);
// kill this so we don't double draw
m_path.reset();
}
catch(Exception ex){}
}
#SuppressLint("NewApi")
#Override
public boolean onTouchEvent(MotionEvent p_event)
{try{
float m_x = p_event.getX();
float m_y = p_event.getY();
switch (p_event.getAction())
{
case MotionEvent.ACTION_DOWN:
touch_start(m_x, m_y);
//touchman(m_x, m_y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(m_x, m_y);
// touchman(m_x, m_y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
//touchman(m_x, m_y);
invalidate();
break;
}
return true;
}
catch(Exception ex){}
return true;
}}

Adding drawable image to background of canvas

I know its possible to paint the background of canvas using
mPaint = new Paint();
mPaint.setColor(Color.RED);
Im just wondering how to i set a permanent background for it. Ive tried using the xml file but nothing happens. Any ideas?
This is the source code of the project, ive been following a tutorial how to do it because im fairly unfamiliar with bitmaps.
Canvas Class
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
public class GameBoard extends View{
private int mFlagX = -1;
private int mFlagY = -1;
private Bitmap mBitmap = null;
private Bitmap nBitmap = null;
private Paint mPaint = null;
private boolean isFlagHidden = false;
private int mBoundX = -1;
private int mBoundY = -1;
//play with these values to make the app more or less challenging
public final int CLOSER = 50;
public final int CLOSE = 100;
public GameBoard(Context context, AttributeSet aSet) {
super(context, aSet);
//load our bitmap
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.star);
//create a paint brush
mPaint = new Paint();
mPaint.setColor(Color.RED);
}
#Override
public void onDraw(Canvas canvas) {
//initialize
if ((mFlagX < 1) || (mFlagY < 1)) {
mFlagX = (int) (getWidth() / 2) - mBitmap.getWidth() / 2;
mFlagY = (int) (getHeight() / 2) - mBitmap.getHeight() / 2;
mBoundX = (int)getWidth() - mBitmap.getWidth();
mBoundY = (int)getHeight() - mBitmap.getHeight();
}
//draw background
canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);
//draw the flag
if (!isFlagHidden) {
canvas.drawBitmap(mBitmap, mFlagX, mFlagY, null);
}
}
public void hideTheFlag(){
//randomize flag location
mFlagX = (int) Math.ceil(Math.random() * mBoundX);
mFlagY = (int) Math.ceil(Math.random() * mBoundY);
isFlagHidden = true;
//force redraw
invalidate();
}
public void giveUp(){
isFlagHidden = false;
//force redraw
invalidate();
}
public Indicators takeAGuess(float x, float y) {
//this is our "warm" area
Rect prettyClose = new Rect(mFlagX - CLOSE, mFlagY - CLOSE, mFlagX+mBitmap.getWidth() + CLOSE, mFlagY+mBitmap.getHeight() + CLOSE);
//normalize
if (prettyClose.left < 0) prettyClose.left = 0;
if (prettyClose.top < 0) prettyClose.top = 0;
if (prettyClose.right > mBoundX) prettyClose.right = mBoundX;
if (prettyClose.bottom > mBoundY) prettyClose.bottom = mBoundY;
//this is our "hot" area
Rect reallyClose = new Rect(mFlagX - CLOSER, mFlagY - CLOSER, mFlagX+mBitmap.getWidth() + CLOSER, mFlagY+mBitmap.getHeight() + CLOSER);
//normalize
if (reallyClose.left < 0) reallyClose.left = 0;
if (reallyClose.top < 0) reallyClose.top = 0;
if (reallyClose.right > mBoundX) reallyClose.right = mBoundX;
if (reallyClose.bottom > mBoundY) reallyClose.bottom = mBoundY;
//this is the area that contains our flag
Rect bullsEye = new Rect(mFlagX, mFlagY, mFlagX+mBitmap.getWidth(), mFlagY+mBitmap.getHeight());
//check to see where on the board the user pressed
if (bullsEye.contains((int) x, (int)y)) {
//found it
isFlagHidden = false;
invalidate();
return Indicators.BULLSEYE;
} else if (reallyClose.contains((int) x, (int)y)) {
//hot
return Indicators.HOT;
} else if (prettyClose.contains((int)x, (int)y)) {
//warm
return Indicators.WARM;
} else {
//not even close
return Indicators.COLD;
}
}
}
Game Class
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class FindTheStar extends Activity implements OnTouchListener, OnClickListener{
private GameBoard mGameBoard = null;
private boolean isFlagHidden = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_star);
mGameBoard = (GameBoard) findViewById(R.id.Hide_canvas);
mGameBoard.setOnTouchListener(this);
Button b = (Button) findViewById(R.id.the_button);
b.setOnClickListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.Hide_canvas) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (isFlagHidden) {
TextView tv = (TextView)findViewById (R.id.the_label);
switch (mGameBoard.takeAGuess(event.getX(), event.getY())) {
case BULLSEYE:
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = false;
b.setText("Go Hide!");
tv.setText("You found me!");
tv.setTextColor(Color.GREEN);
break;
case HOT:
tv.setText("You're hot!");
tv.setTextColor(Color.RED);
break;
case WARM:
tv.setText("Getting warm...");
tv.setTextColor(Color.YELLOW);
break;
case COLD:
tv.setText("You're cold.");
tv.setTextColor(Color.BLUE);
break;
}
}
}
return true;
}
return false;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.the_button) {
TextView tv = (TextView)findViewById (R.id.the_label);
tv.setText("");
Button b = (Button) findViewById(R.id.the_button);
isFlagHidden = !isFlagHidden;
if (isFlagHidden) {
b.setText("Can't find me?");
mGameBoard.hideTheFlag();
} else {
b.setText("Go Hide!");
mGameBoard.giveUp();
}
}
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/the_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textSize="20sp"
android:layout_marginBottom="10dip"
android:text="Lets Play Hide and Seek!"/>
<Button
android:id="#+id/the_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:layout_marginBottom="10dip"
android:text="Go Hide!"/>
<app.autismapp.GameBoard
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/Hide_canvas"/>
</LinearLayout>
yes you can set your permanent background using xml layout..i done this by creating two class.
this is my code in MainACtivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final BrushView view=new BrushView(this);
setContentView(R.layout.mylayout);//removed this one if the paint doesnt work
view.setBackgroundResource(R.drawable.background);//to set background
setContentView(view);// to display the background
and my second class
public class PaintView extends View {
private Paint paint = new Paint();
public LayoutParams params;
public PaintView(Context context) {
super(context);
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
i hope it gives you an idea

Adding Huge Canvas in the ScrollView in Android

In my android application, I want to add a huge canvas in a scrollView because if I draw a huge line I need to see with scrolling option.
But I am getting error in LogCat:
01-01 11:42:14.452: E/AndroidRuntime(1706): java.lang.RuntimeException: Unable to start
activity ComponentInfo{com.example.list2/com.example.list2.MainActivity}:
java.lang.NullPointerException
layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp" >
<View
android:id="#+id/mapview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
activity
package com.example.list2;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.widget.ScrollView;
public class MainActivity extends Activity{
Map map;
public void onCreate(Bundle saved){
super.onCreate(saved);
setContentView(R.layout.activity_main);
ScrollView scrollView = new ScrollView(this);
scrollView.addView(map);
setContentView(scrollView);
}
public void Draw(){
map = new Map(this);
map.setBackgroundColor(Color.BLACK);
setContentView(map);
}
public class Map extends View {
Paint paint = new Paint();
public Map(Context context) {
super(context);
}
#Override
public void onDraw(Canvas canvas) {
paint.setColor(Color.RED);
canvas.drawCircle(100, 100, 20, paint);
canvas.drawLine(2000, 2000, 5000, 5000, paint);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Compute the height required to render the view
// Assume Width will always be MATCH_PARENT.
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = 3000 + 50; // Since 3000 is bottom of last Rect to be drawn added and 50 for padding.
setMeasuredDimension(width, height);
}
}
}

Categories

Resources