Adding animatedView to existing layout - android

Ok, so here is my full code:
package com.example.theball;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
#SuppressLint("NewApi")
#SuppressWarnings("unused")
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;
AnimatedView animatedView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
public static final int width = 50;
public static final int height = 50;
public boolean firstDraw = true;
private int screen_width;
private int screen_height;
private int sensorX;
private Timer t;
private int TimeCounter = 0;
private TextView highscore_int;
private int sensorY;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
highscore_int = (TextView) findViewById(R.id.highscore_int);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(this);
setContentView(animatedView);
t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
TimeCounter++;
}
});
}
}, 0, 1000);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
sensorY = (int) event.values[1];
sensorX = (int) event.values[0];
x -= sensorX * 3;
y += sensorY * 3;
if (x <= 0 || x >= screen_width || y <= 0 || y >= screen_height) {
finish();
Intent myIntent = new Intent(this, YouLost.class);
startActivity(myIntent);
}
}
}
public class AnimatedView extends ImageView {
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
static final int width = 50;
static final int height = 50;
#SuppressLint("NewApi")
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
display.getSize(size);
screen_width = size.x;
screen_height = size.y;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xffffAC23);
mDrawable.setBounds(0, 0, screen_width, screen_height);
}
#Override
protected void onDraw(Canvas canvas) {
mDrawable.setBounds(x, y, x + width, y + height);
if (firstDraw) {
x = screen_width / 2;
y = screen_height / 2;
firstDraw = false;
}
mDrawable.draw(canvas);
invalidate();
}
}
}
My problem is, I want to use the activity_main layout and still have the animatedView, How can I do it? Please, don't say my problem is I set twice the setContentView, I KNOW I DID IT! That's because I want a ball and a layout.
Here someone else with my problem:http://stackoverflow.com/questions/22580336/android-animatedview-taking-up-whole-activity-screen .
The animatedView creating an empty layout for himself, if I will delete the "setContentView(animatedView)" I will have my layout but not my ball.
Now I have an empty layout with a ball.

Can you please post your XML for activity_main?
It sounds like what you want to do is create a FrameLayout as the top-level view in your activity layout. This will allow you to stack child views on top of one another. Then, after your call to setContentView(R.layout.activity_main), you can do something like this:
FrameLayout myRootLayout = (FrameLayout) findViewById(R.id.id_of_top_level_framelayout);
animatedView = new AnimatedView(this);
myRootLayout.addView(animatedView);
Alternately you can use addView(animatedView, index) if you want to specify the z-order of the animatedView.
Please clarify if I misunderstood your question.

Related

Having trouble switching activities

I have two activities: a menu, and a game. I have them both set up as surface views, and when I click the "start" button on the menu activity, it starts the game activity. Then I want it to save the score and return to the menu activity when the player crashes. Both activities have separate threads that start with the activity, so when I tried to re-launch the menu activity from the game, I was getting an exception that the thread was already started. So to avoid this, I had the game activity finish the menu activity when it started so that relaunching the menu activity would also restart the thread. Now I'm getting an exception that the canvas is already locked. Do I need to unlock the canvas before finishing the activity? And is there a better way for me to handle switching between activities?
MainActivity:
package com.mikey.******;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity {
public static Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GamePanel(this));
}
}
GamePanel Layout:
package com.mikey.*****;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.preference.PreferenceManager;
import android.support.v4.app.NavUtils;
import android.util.AttributeSet;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.Random;
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
private static SharedPreferences prefs;
public static int width;
public static int height;
public static int screenX, screenY;
private Canvas c;
private MainThread thread;
private Background bg;
private Scoreboard sb;
public int moveSpeed = 10;
private Player player;
private ArrayList<Smokepuff> smoke;
private Plunger plunger;
private Plunger plunger1;
private long smokeStart;
private long smokeTime;
public int score = 0;
public boolean isPlaying;
private Bitmap bgImg;
private Bitmap b;
private int scaleFactor = 2;
private long timer;
private long timeStart;
private Paint paint;
private ArrayList<Coin> coin;
private long coinTime;
private int coinDelay;
private Bitmap coinImg;
public boolean playable;
public int distance;
private int plungerDelay;
private int plungerReset;
private long plungerTime;
private int coinSet;
private Menu endMenu;
public GamePanel(Context context){
super(context);
prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenX=size.x;
screenY=size.y;
getHolder().addCallback(this);
thread = new MainThread(getHolder(), this);
setFocusable(true);
paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(40);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
boolean retry = true;
int count = 0;
while(retry&&count<1000){
try{thread.setRunning(false);
thread.join();
retry=false;
}catch(InterruptedException e){}
count++;
}
}
#Override
public void surfaceCreated(SurfaceHolder holder){
thread.setRunning(true);
thread.start();
//moveSpeed = -20;
bgImg = BitmapFactory.decodeResource(getResources(), R.drawable.bg2);
width = bgImg.getWidth();
height = bgImg.getHeight();
bg = new Background(bgImg);
sb = new Scoreboard(getContext());
plunger = new Plunger(BitmapFactory.decodeResource(getResources(), R.drawable.plunger));
plunger1 = new Plunger(BitmapFactory.decodeResource(getResources(),R.drawable.plunger));
player = new Player(BitmapFactory.decodeResource(getResources(), R.drawable.potty));
smoke = new ArrayList<Smokepuff>();
coin = new ArrayList<Coin>();
//Random r = new Random();
coinImg = BitmapFactory.decodeResource(getResources(),R.drawable.coin2);
coin.add(new Coin(coinImg));
coinDelay = 5;
playable = true;
}
#Override
public boolean onTouchEvent(MotionEvent event){
if(event.getAction()==MotionEvent.ACTION_DOWN){
if(!isPlaying&&playable){
isPlaying=true;
smokeStart = System.nanoTime();
timeStart = System.nanoTime();
plungerReset = distance;
plungerDelay = 100;
coinSet = distance;
}
player.setAccelerate(true);
player.setUp(true);
return true;
}
else if(event.getAction()==MotionEvent.ACTION_UP){
player.setAccelerate(false);
player.setUp(false);
return true;
}
return super.onTouchEvent(event);
}
public void update(){
if(isPlaying) {
timer = (System.nanoTime() - timeStart) / 1000000;
distance+=(timer*moveSpeed)/1000;
if (timer > 50) {
if(player.getAccelerate()&&!player.maxAlt) {
moveSpeed += 1;
}else if(!player.getAccelerate()&&!player.maxAlt){
if(moveSpeed>0){
if(distance<200){
moveSpeed-=.05;
}else {
moveSpeed -= .18;
}
}
}
timeStart = System.nanoTime();
}
//moveSpeed += score;
smokeTime = (System.nanoTime()-smokeStart)/1000000;
if(smokeTime>100){
smoke.add(new Smokepuff(player.getX(),player.getY()+5));
smokeStart=System.nanoTime();
}
if(distance>300&&plungerDelay+plungerReset<distance){
plunger.setX(screenX);
plunger1.setX(screenX+500);
Random q = new Random();
plungerDelay = q.nextInt(150)+100;
plungerReset = distance;
}
if(distance-coinSet>coinDelay) {
Random z = new Random();
int num = z.nextInt(3) + 1;
for (int i = 0; i < num; i++) {
coin.add(new Coin(coinImg));
}
Random r = new Random();
coinDelay = r.nextInt(50) + 1;
coinSet=distance;
}
plunger.update(moveSpeed);
plunger1.update(moveSpeed);
int dy = player.update();
bg.update(moveSpeed, dy);
for(int i=0;i<coin.size();i++){
coin.get(i).update(moveSpeed);
if(coin.get(i).getX()<-10){
coin.remove(i);
}else if (collision(coin.get(i), player)) {
coin.remove(i);
score+=10;
}
}
if(collision(player,plunger)){
plunger.setX(player.getX() + player.getWidth() - 1);
plunger.setY(player.getY()+player.height/2);
if(!plunger.attached){
plungerTime = System.nanoTime();
plunger.attached = true;
}
if(moveSpeed>10){
moveSpeed--;
}
}
if(plunger.getX()<-100){
plunger.reset();
}
if(collision(player,plunger1)){
plunger1.setX(player.getX() + player.getWidth()-1);
plunger1.setY(player.getY()+player.height/2);
if(!plunger1.attached) {
plungerTime = System.nanoTime();
plunger1.attached=true;
}
if(moveSpeed>10){
moveSpeed--;
}
}
if(plunger1.getX()<-100){
plunger1.reset();
}
if((System.nanoTime()-plungerTime)/1000000>750){
if(collision(plunger,player)){
plunger.reset();
plunger.attached = false;
}
if(collision(plunger1,player)){
plunger1.reset();
plunger1.attached = false;
}
}
for(int i=0;i<smoke.size();i++){
smoke.get(i).update(moveSpeed);
if(smoke.get(i).getX()<-10||smoke.get(i).getY()<0){
smoke.remove(i);
}
}
sb.update(score, distance);
if(2*player.getY()>screenY-300){
SharedPreferences.Editor editor = prefs.edit();
if(!prefs.contains("highscore")) {
editor.putInt("highscore", score);
//return;
}else if(prefs.getInt("highscore",0)<score){
editor.putInt("highscore",score);
}
editor.commit();
isPlaying=false;
playable=false;
endGame();
//NavUtils.navigateUpFromSameTask(MainActivity.activity);
Intent intent = new Intent(getContext(),Menu.class);
getContext().startActivity(intent);
}
}
}
public boolean collision(GameObject a, GameObject b){
if(Rect.intersects(a.getRect(),b.getRect())){
return true;
}
return false;
}
#Override
public void draw(Canvas canvas){
final float scaleFactorX = (float) 2;
final float scaleFactorY = (float) 2;
if(canvas!=null){
c = canvas;
final int savedState = canvas.save();
canvas.scale(scaleFactorX, scaleFactorY);
bg.draw(canvas);
for(Coin c:coin){
c.draw(canvas);
}
plunger.draw(canvas);
plunger1.draw(canvas);
for(Smokepuff sp:smoke){
sp.draw(canvas);
}
player.draw(canvas);
if((isPlaying&&playable)||(!isPlaying&&!playable)) {
sb.draw(canvas);
}
canvas.restoreToCount(savedState);
canvas.drawText(Integer.toString(moveSpeed), screenX-100,40,paint);
}
//bg.draw(canvas);
}
public void endGame(){
SharedPreferences.Editor editor = prefs.edit();
if(!prefs.contains("highscore")) {
editor.putInt("highscore", score);
return;
}else if(prefs.getInt("highscore",0)<score){
editor.putInt("highscore",score);
}
editor.commit();
Intent intent = new Intent(getContext(),Menu.class);
getContext().startActivity(intent);
}
}
Menu Activity:
package com.mikey.*****;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
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.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
public class Menu extends Activity{
//private ImageButton upgrade;
private int screenY;
private int screenX;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
screenY = getWindow().getDecorView().getHeight();
screenX = getWindow().getDecorView().getWidth();
setContentView(new MenuLayout(this));
/*upgrade = (ImageButton) findViewById(R.id.upgrade);
upgrade.setX(-150);
upgrade.setY(1080-130);
upgrade.setScaleX(4);
upgrade.setScaleY(4);*/
}
#Override
protected void onPause(){
super.onPause();
finish();
}
}
MenuLayout:
package com.mikey.*****;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.RadialGradient;
import android.graphics.RectF;
import android.graphics.Shader;
import android.preference.PreferenceManager;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import java.util.ArrayList;
import java.util.Random;
public class MenuLayout extends SurfaceView implements SurfaceHolder.Callback {
private static SharedPreferences prefs;
private MenuThread thread;
private boolean played;
private int screenX, screenY;
private Bitmap upgrade;
private Bitmap map;
private Bitmap bg;
private Bitmap launch;
private Bitmap potty;
private Bitmap cloudA;
private Bitmap cloudB;
private ArrayList<Cloud> cloud;
private UpgradeBtn upgradeBtn;
private MapBtn mapBtn;
private LaunchBtn launchBtn;
//private Paint bg;
private Paint feature;
private Paint border;
private Paint featureRad;
private Paint stick;
private Paint text;
private Paint shadow;
private int x;
private int y;
private boolean upg;
private boolean showmap;
private boolean start;
public MenuLayout(Context context){
super(context);
prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
getHolder().addCallback(this);
thread = new MenuThread(getHolder(),this);
setFocusable(true);
screenX=size.x;
screenY=size.y;
upgrade = BitmapFactory.decodeResource(getResources(),R.drawable.blueprint);
map = BitmapFactory.decodeResource(getResources(),R.drawable.map);
launch = BitmapFactory.decodeResource(getResources(),R.drawable.launch);
bg = BitmapFactory.decodeResource(getResources(),R.drawable.menu_bg);
potty = BitmapFactory.decodeResource(getResources(),R.drawable.potty1);
cloudA = BitmapFactory.decodeResource(getResources(),R.drawable.cloud1);
cloudB = BitmapFactory.decodeResource(getResources(),R.drawable.cloud2);
upgradeBtn = new UpgradeBtn(upgrade,screenY);
mapBtn = new MapBtn(map);
launchBtn = new LaunchBtn(launch,screenX,screenY);
cloud = new ArrayList<>();
for(int i =0;i<4;i++){
addCloud();
}
start = true;
//bg = new Paint();
//bg.setColor(Color.WHITE);
shadow = new Paint();
shadow.setAntiAlias(true);
shadow.setColor(Color.WHITE);
shadow.setTextSize(45.0f);
shadow.setStrokeWidth(2.0f);
shadow.setStyle(Paint.Style.STROKE);
shadow.setShadowLayer(10.0f, 20.0f, -20.0f, Color.BLACK);
Shader shader = new LinearGradient(0, 0, 0, 90, Color.LTGRAY, Color.DKGRAY, Shader.TileMode.CLAMP);
feature = new Paint();
feature.setShader(shader);
border = new Paint();
border.setColor(Color.BLACK);
border.setStyle(Paint.Style.STROKE);
border.setStrokeWidth(8);
Shader shader1 = new RadialGradient(screenX-60,60,150,Color.LTGRAY,Color.DKGRAY, Shader.TileMode.MIRROR);
featureRad = new Paint();
featureRad.setShader(shader1);
stick = new Paint();
stick.setColor(Color.BLACK);
stick.setStrokeWidth(20);
text = new Paint();
text.setColor(Color.WHITE);
text.setTextSize(50);
}
public void addCloud(){
Bitmap img;
Random r = new Random();
Random p = new Random();
Random q = new Random();
int s = r.nextInt(10);
if(s>5){
Matrix m = new Matrix();
float h = r.nextFloat()+1;
m.setRectToRect(new RectF(0, 0, cloudA.getWidth(), cloudA.getHeight()),
new RectF(0, 0, cloudA.getWidth()*h, cloudA.getHeight()*h), Matrix.ScaleToFit.CENTER);
img = Bitmap.createBitmap(cloudA, 0, 0, cloudA.getWidth(), cloudA.getHeight(), m, true);
}else{
img = cloudB;
}
if(start){
x = -img.getWidth();
}
else{
x = p.nextInt(screenX);
}
cloud.add(new Cloud(img,x,p.nextInt(screenY-750)+100,q.nextInt(8)+1,screenX));
}
public Bitmap highlightImage(Bitmap src, int color,boolean x, boolean y) {
int xMod;
int yMod;
if(x){
xMod = 4;
}else{
xMod = -1;
}
if(y){
yMod = 2;
}
else{
yMod = -1;
}
// create new bitmap, which will be painted and becomes result image
Bitmap bmOut = Bitmap.createBitmap(src.getWidth()*5/4+30, src.getHeight()*5/4+30, Bitmap.Config.ARGB_8888);
// setup canvas for painting
Canvas canvas = new Canvas(bmOut);
canvas.scale(1.25f,1.25f);
// setup default color
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
// create a blur paint for capturing alpha
Paint ptBlur = new Paint();
ptBlur.setMaskFilter(new BlurMaskFilter(15, BlurMaskFilter.Blur.NORMAL));
int[] offsetXY = new int[2];
// capture alpha into a bitmap
Bitmap bmAlpha = src.extractAlpha(ptBlur, offsetXY);
// create a color paint
Paint ptAlphaColor = new Paint();
ptAlphaColor.setColor(color);
// paint color for captured alpha region (bitmap)
canvas.drawBitmap(bmAlpha, xMod*offsetXY[0]/2, yMod*offsetXY[1], ptAlphaColor);
// free memory
bmAlpha.recycle();
// paint the image source
canvas.drawBitmap(src, 0, 0, null);
// return out final image
return bmOut;
}
public void launchUpgrade(){
upg = true;
upgradeBtn.setImg(upgrade);
}
public void launchMap(){
showmap = true;
mapBtn.setImg(map);
}
public void launchProfile(){
}
public void startGame(){
launchBtn.setImg(launch);
Intent myIntent = new Intent(getContext(), MainActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
getContext().startActivity(myIntent);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if(!thread.getRunning()) {
thread.setRunning(true);
thread.start();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){}
#Override
public void surfaceDestroyed(SurfaceHolder holder){
boolean retry = true;
int count = 0;
if(thread.getRunning()) {
thread.interrupt();
}
/*while(retry&&count<1000){
try{thread.setRunning(false);
thread.join();
retry=false;
}catch(InterruptedException e){}
count++;
}*/
}
#Override
public boolean onTouchEvent(MotionEvent event) {
x =(int) event.getX();
y =(int) event.getY();
if (x < 710 && y > 780) {
upgradeBtn.setImg(highlightImage(upgrade,Color.BLUE,false,true));
}else{
upgradeBtn.setImg(upgrade);
}
if (x < 520 && y < 275) {
mapBtn.setImg(highlightImage(map,Color.YELLOW,true,false));
}else{
mapBtn.setImg(map);
}
if(x>1500&&y>700){
launchBtn.setImg(highlightImage(launch,Color.RED,true,true));
}else{
launchBtn.setImg(launch);
}
if(event.getAction()==MotionEvent.ACTION_UP) {
if (x < 710 && y > 780) {
launchUpgrade();
return true;
}
if (x < 520 && y < 275) {
launchMap();
return true;
}
if(x>1700&&y<235){
launchProfile();
return true;
}
if(x>1500&&y>700){
startGame();
}
}
return true;
}
public void update(){
for(int i=0;i<cloud.size();i++){
cloud.get(i).update();
if(cloud.get(i).getX()>screenX){
cloud.remove(i);
addCloud();
}
}
}
#Override
public void draw(Canvas canvas){
if(canvas!=null) {
canvas.drawBitmap(bg,-3,0,null);
for(int i=0;i<cloud.size();i++){
cloud.get(i).draw(canvas);
}
canvas.drawBitmap(potty, screenX / 2 - 190, screenY / 2 - 190, null);
//canvas.drawBitmap(upgrade, -235, screenY - upgrade.getHeight() + 300, null);
canvas.drawRoundRect(screenX - 550, 5, screenX - 150, 105, 15, 15, feature);
canvas.drawRoundRect(screenX - 550, 5, screenX - 150, 105, 25, 25, border);
canvas.drawCircle(screenX - 60, 60, 150, featureRad);
canvas.drawCircle(screenX - 60, 60, 150, border);
canvas.drawCircle(screenX / 2 + 230, screenY / 2 + 110, 50, stick);
canvas.drawLine(screenX / 2 + 220, screenY / 2 + 110, screenX / 2 + 185, screenY / 2 + 340, stick);
canvas.drawLine(screenX / 2 + 185, screenY / 2 + 340, screenX / 2 + 270, screenY/2+440,stick);
canvas.drawLine(screenX/2+270,screenY/2+440,screenX/2+270,screenY,stick);
canvas.drawLine(screenX/2+270,screenY/2+440,screenX/2+340,screenY,stick);
canvas.drawLine(((screenX / 2 + 220)+(screenX / 2 + 185))/2,screenY/2+230,screenX/2+210,
screenY/2+250,stick);
canvas.drawLine(screenX/2+185,screenY/2+250,screenX/2+245,screenY/2+235,stick);
canvas.drawLine(screenX / 2 + 235, screenY / 2 + 245, ((screenX / 2 + 220) + (screenX / 2 + 185)) / 2,
screenY / 2 + 230, stick);
canvas.drawText(Integer.toString(prefs.getInt("highscore", 0)), 1000, 50, text);
upgradeBtn.draw(canvas);
mapBtn.draw(canvas);
launchBtn.draw(canvas);
canvas.drawText(Integer.toString(x)+","+Integer.toString(y),50,50,text);
/*if(upg){
canvas.drawText("UPGRADE",540,400,text);
canvas.drawBitmap(highlightImage(upgrade), -235, screenY - upgrade.getHeight() + 300,null);
}*/
if(showmap){
canvas.drawText("MAP",540,500,text);
}
}
}
}
I'm sure there is a lot more wrong with my code than just the issue I'm having because I'm very new to this, so if you have any general suggestions to clean up my code, I'd love to hear those as well.

How to make my app intent to an other screen when something happens

Well, I have an app with a ball, moving using the accelerometer sensor, now, I want it to intent me to the screen "GameOver.java" when the ball is touching the corners (top,bottom,left and right of the screen).
Here is my code :
package com.example.theball;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
#SuppressWarnings("deprecation") public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;
AnimatedView animatedView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(this);
setContentView(animatedView);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
x -= (int) event.values[0];
y += (int) event.values[1];
}
}
public class AnimatedView extends ImageView {
static final int width = 50;
static final int height = 50;
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xffffAC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
#Override
protected void onDraw(Canvas canvas) {
mDrawable.setBounds(x, y, x + width, y + height);
mDrawable.draw(canvas);
invalidate();
}
}
}
Assuming I understand your question correctly:
Every time the ball moves -- in your onSensorChanged(..) method -- you need to check if x == upper x bound or lower x bound and if y == upper y bound or lower y bound... If any of these conditions resolves to true that means the center of the ball is touching an edge and GameOver.java should be started:
EDIT:
// where 0 is the lower bound and 50 is the upper bound of our canvas
if(x <= 0 || x >= 50 || y <= 0 || y >= 50) {
Intent myIntent = new Intent(this, GameOver.class);
startActivity(myIntent);
}

Move an object using accelerometer

Hello :) I created a yellow canvas with a ball on it, now i'm trying to move the ball but I don't know how, it's the first time i'm using an accelerometer and it's my first time using canvas and draw.. So can you help me moving it?
Here is my code so far:
package com.example.theball;
import android.support.v4.widget.DrawerLayout.LayoutParams;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.SensorEvent;
import android.os.Bundle;
import android.view.Display;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
private int c = Color.YELLOW;
private Canvas g;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
draw();
}
#SuppressWarnings("deprecation")
public void draw ()
{
Display display = getWindowManager().getDefaultDisplay();
int width = display.getHeight();
int height = display.getWidth();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.RGB_565);
g = new Canvas(bitmap);
g.drawColor(c);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
g.drawCircle(50, 10, 25, paint);
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(bitmap);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
layout.addView(imageView, params);
layout.setBackgroundColor(Color.BLACK);
setContentView(layout);
}
public void onSensorChanged(SensorEvent event)
{
}
}
SOLVED: here is the new code, thanks to someone here from stackoverflow:
package com.example.theball;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
#SuppressWarnings("deprecation") public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor accelerometer;
private long lastUpdate;
AnimatedView animatedView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
lastUpdate = System.currentTimeMillis();
animatedView = new AnimatedView(this);
setContentView(animatedView);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
x -= (int) event.values[0];
y += (int) event.values[1];
}
}
public class AnimatedView extends ImageView {
static final int width = 50;
static final int height = 50;
public AnimatedView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xffffAC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
#Override
protected void onDraw(Canvas canvas) {
mDrawable.setBounds(x, y, x + width, y + height);
mDrawable.draw(canvas);
invalidate();
}
}
}

Move Ball around screen. Accelerometer. Bounce too

I have to do an app in Android that moves a ball around the screen. I need to move the ball with the accelerometer.
I have this code but the ball go around the border and doesn't bounce.
package com.example.test2;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
public class test2 extends Activity implements SensorEventListener {
CustomDrawableView mCustomDrawableView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public float xPosition, xAcceleration, xVelocity = 0.0f;
public float yPosition, yAcceleration, yVelocity = 0.0f;
public float xmax, ymax;
private Bitmap mBitmap;
private Bitmap mWood;
private SensorManager sensorManager = null;
public float frameTime = 0.666f;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set FullScreen & portrait
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Get a reference to a SensorManager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
mCustomDrawableView = new CustomDrawableView(this);
setContentView(mCustomDrawableView);
// setContentView(R.layout.main);
// Calculate Boundry
Display display = getWindowManager().getDefaultDisplay();
xmax = (float) display.getWidth() - 50;
ymax = (float) display.getHeight() - 50;
}
// This method will update the UI on new sensor events
public void onSensorChanged(SensorEvent sensorEvent) {
{
if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
// Set sensor values as acceleration
yAcceleration = sensorEvent.values[1];
xAcceleration = sensorEvent.values[2];
updateBall();
}
}
}
private void updateBall() {
// Calculate new speed
xVelocity += (xAcceleration * frameTime);
yVelocity += (yAcceleration * frameTime);
// Calc distance travelled in that time
float xS = (xVelocity / 2) * frameTime;
float yS = (yVelocity / 2) * frameTime;
// Add to position negative due to sensor
// readings being opposite to what we want!
xPosition -= xS;
yPosition -= yS;
if (xPosition > xmax) {
xPosition = xmax;
} else if (xPosition < 0) {
xPosition = 0;
}
if (yPosition > ymax) {
yPosition = ymax;
} else if (yPosition < 0) {
yPosition = 0;
}
}
// I've chosen to not implement this method
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
SensorManager.SENSOR_DELAY_GAME);
}
#Override
protected void onStop() {
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
public class CustomDrawableView extends View {
public CustomDrawableView(Context context) {
super(context);
Bitmap ball = BitmapFactory.decodeResource(getResources(),
R.drawable.ball);
final int dstWidth = 50;
final int dstHeight = 50;
mBitmap = Bitmap
.createScaledBitmap(ball, dstWidth, dstHeight, true);
mWood = BitmapFactory.decodeResource(getResources(),
R.drawable.wood);
}
protected void onDraw(Canvas canvas) {
final Bitmap bitmap = mBitmap;
canvas.drawBitmap(mWood, 0, 0, null);
canvas.drawBitmap(bitmap, xPosition, yPosition, null);
invalidate();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
How can I solve it?
Thank you
You want to move it with the accelerometer, but you're registering an orientation sensor listener. Register for the accelerometer instead.

Is it possible to have more than one setContentView in one class?

I am trying to print the rectangle shape and the main xml aswell as I want the shape and the figures, is this possible? If not how can I print a shape from java code and my main xml both on to my emulator? Thank you
package com.example.accel;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class AccelActivity extends Activity implements SensorEventListener
{
/** Called when the activity is first created. */
CustomDrawableView mCustomDrawableView = null;
ShapeDrawable mDrawable = new ShapeDrawable();
public static int x;
public static int y;
public static int z;
private SensorManager sensorManager = null;
TextView x1, y1, z1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get a reference to a SensorManager
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mCustomDrawableView = new CustomDrawableView(this);
setContentView(mCustomDrawableView);
setContentView(R.layout.main);
}
// This method will update the UI on new sensor events
public void onSensorChanged(SensorEvent sensorEvent)
{
{
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
TextView tvX= (TextView)findViewById(R.id.x_axis);
TextView tvY= (TextView)findViewById(R.id.y_axis);
TextView tvZ= (TextView)findViewById(R.id.z_axis);
x = (int) Math.pow(sensorEvent.values[0], 2);
y = (int) Math.pow(sensorEvent.values[1], 2);
z = (int) Math.pow(sensorEvent.values[2], 2);
}
// if (sensorEvent.sensor.getType() == Sensor.TYPE_ORIENTATION) {
// }
}
}
// I've chosen to not implement this method
public void onAccuracyChanged(Sensor arg0, int arg1)
{
// TODO Auto-generated method stub
}
#Override
protected void onResume()
{
super.onResume();
// Register this class as a listener for the accelerometer sensor
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
// ...and the orientation sensor
}
#Override
protected void onStop()
{
// Unregister the listener
sensorManager.unregisterListener(this);
super.onStop();
}
public class CustomDrawableView extends View
{
static final int width = 150;
static final int height = 250;
public CustomDrawableView(Context context)
{
super(context);
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas)
{
RectF rect = new RectF(AccelActivity.x, AccelActivity.y, AccelActivity.x + width, AccelActivity.y
+ height); // set bounds of rectangle
Paint p = new Paint(); // set some paint options
p.setColor(Color.BLUE);
canvas.drawRect(rect, p);
invalidate();
}
}
}
yes, you can.
setcontentview(anotherLayout), so you pring the new layout in your activity.
or you can define other elements in your mainLayout and you manipulate it by the function setVisibily
if you need elementA:
elementA = findViewById(R.id.elementA);
elementA.setVisibility(true);
and if you don't need it:
elementA.setVisibility(false);

Categories

Resources