If I want to add a button in this class so that I can call the onclicklistener, how should I do it?i have also provided the activity class onto which i am adding this view.
activity:
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.content.Context;
public class NewGame extends Activity {
View view;
Context context;
RelativeLayout layout;
GameView gameview;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
gameview=new GameView(this);
setContentView(gameview);
//layout = (RelativeLayout) findViewById(R.id.relative_layout);
//layout.addView(gameview);
}
}
view:
public class GameView extends View {
Path circle;
Paint cPaint;
Paint tPaint;
String z;
int i = 65, strt, arc, leftx, topy, rightx, bottomy, maxx, maxy;
boolean flag1, flag2, flag3;
double n1, n2;
int n, n3 = 180,n4,n5 = 90;
float f1 = 180, f2 = 90;
Button b1;
Random r = new Random();
RectF oval;
public GameView(Context context) {
super(context);
leftx = 0;
topy = 60;
rightx = 150;
bottomy = 120;
z = String.valueOf(Character.toChars(i));
cPaint = new Paint();
cPaint.setColor(Color.RED);
strt = 45;
arc = 315;
n1 = Math.random() * 600;
Log.d("random", z);
if (flag2 == false)
new DrawThread(this);
// cPaint.setStrokeWidth(2);
tPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
tPaint.setStyle(Paint.Style.FILL_AND_STROKE);
tPaint.setColor(Color.BLACK);
float scale = getResources().getDisplayMetrics().scaledDensity;
tPaint.setTextSize(20 * scale);
}
public void onSizeChanged(int w,int h,int oldh,int oldw) {
maxx = oldw;
maxy = oldh;
}
//#Override
protected void onDraw(Canvas canvas) {
// Drawing commands go here
oval = new RectF(leftx,topy,rightx,bottomy);
canvas.drawArc(oval, strt, arc, true, cPaint);
while (i < 90) {
canvas.drawText(String.valueOf(Character.toChars(i)),f1,f2, tPaint);
break;
}
}
}
You can do it like this:
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
And then you can do this
bt.setOnClickListener(new View.OnClickListener() {
//TO DO
}
I hope that this can help you.
first of all in order to allow to your custom view to have an addView(View v) method it must extend ViewGroup instead of View; then you can use this code
b1=new Button(context);
b1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT ));
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
this.addView(b1);
Related
I am working on a android launcher that shows the 1st 4 app icons in a grid view however I'm trying to display the folder as a square shape it's showing up as a circle shape...
heres my code:
package appname.launcher.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.Region;
import android.graphics.drawable.Drawable;
import android.view.View;
import Appname.launcher.activity.Home;
public class GroupIconDrawable extends Drawable{
private int outlinepad;
Bitmap[] icons;
public int iconSize;
Paint paint;
Paint paint2;
Paint paint4;
private int iconSizeDiv2;
private int padding;
private float scaleFactor = 1;
private boolean needAnimate,needAnimatScale;
public View v;
private float sx = 1;
private float sy = 1 ;
public GroupIconDrawable(Bitmap[] icons,int size){
init(icons,size);
}
private void init(Bitmap[] icons,int size){
this.icons = icons;
this.iconSize = size;
iconSizeDiv2 = Math.round(iconSize / 2f);
padding = iconSize /25;
this.paint = new Paint();
paint.setColor(Color.WHITE);
paint.setAlpha(200);
paint.setAntiAlias(true);
this.paint4 = new Paint();
paint4.setColor(Color.WHITE);
paint4.setAntiAlias(true);
paint4.setFlags(Paint.ANTI_ALIAS_FLAG);
paint4.setStyle(Paint.Style.STROKE);
outlinepad = Tools.convertDpToPixel(2, Home.desktop.getContext());
paint4.setStrokeWidth(outlinepad);
this.paint2 = new Paint();
paint2.setAntiAlias(true);
paint2.setFilterBitmap(true);
}
public GroupIconDrawable(Bitmap[] icons,int size,View v){
init(icons,size);
this.v =v;
}
public void popUp(){
sy = 1;
sx = 1;
needAnimate = true;
needAnimatScale = true;
invalidateSelf();
}
public void popBack(){
needAnimate = false;
needAnimatScale = false;
invalidateSelf();
}
#Override
public void draw(Canvas canvas) {
canvas.save();
if (needAnimatScale){
scaleFactor = Tools.clampFloat(scaleFactor-0.09f,0.5f,1f);
}else {
scaleFactor = Tools.clampFloat(scaleFactor+0.09f,0.5f,1f);
}
if (v == null)
canvas.scale(scaleFactor,scaleFactor,iconSize/2,iconSize/2);
else
canvas.scale(scaleFactor,scaleFactor,iconSize/2,v.getHeight() / 2);
if (v!= null)
canvas.translate(0,v.getHeight()/2-iconSize/2);
Path clipp = new Path();
clipp.addCircle(iconSize / 2,iconSize / 2,iconSize / 2-outlinepad, Path.Direction.CW);
canvas.clipPath(clipp, Region.Op.REPLACE);
canvas.drawBitmap(icons[0],null,new Rect(padding,padding, iconSizeDiv2-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[1],null,new Rect(iconSizeDiv2+padding,padding,iconSize-padding, iconSizeDiv2-padding),paint2);
canvas.drawBitmap(icons[2],null,new Rect(padding, iconSizeDiv2+padding, iconSizeDiv2-padding,iconSize-padding),paint2);
canvas.drawBitmap(icons[3],null,new Rect(iconSizeDiv2+padding, iconSizeDiv2+padding,iconSize-padding,iconSize-padding),paint2);
canvas.clipRect(0,0,iconSize,iconSize, Region.Op.REPLACE);
canvas.restore();
if (needAnimate){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()-25,0,255));
invalidateSelf();
}else if (paint2.getAlpha() != 255){
paint2.setAlpha(Tools.clampInt(paint2.getAlpha()+25,0,255));
invalidateSelf();
}
}
#Override
public void setAlpha(int i) {}
#Override
public void setColorFilter(ColorFilter colorFilter) {}
#Override
public int getOpacity() {return 0;}
}
I think its because of the > clipp.addCircle(iconSize / 2,iconSize /
2,iconSize / 2-outlinepad,> Path.Direction.CW); code but i'm not sure
how would I make it a square instead of a circle?
change your clipp Path usage from addCircle to be addRect(float left, float top, float right, float bottom, Path.Direction dir)
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.
When the play button is pressed to start the game(activity), I'd like to create the instance of a ball falling from the top of the screen (the ball will hit something later). I'm not sure how to go about it. Can anyone assist?
What I'm working with so far:
public class GameActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Turn title off
requestWindowFeature(Window.FEATURE_NO_TITLE);
// set Game to fullscreen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
View ballView = new BallView(this);
setContentView(ballView);
// ballView.setBackgroundColor(Color.TRANSPARENT);
}
}
and
public class BallView extends View {
// Ball attributes
private float ballRadius = 30;
private float ballX = 50;
private float ballY = 50;
private RectF ballBounds;
private Paint ballColor;
// For game elements
private int score = 0;
public BallView(Context context){
super(context);
// Initialize game elements
ballBounds = new RectF();
ballColor = new Paint();
this.setFocusableInTouchMode(true);
}
public void onDraw(Canvas canvas){
// Draw ball
ballBounds.set(ballX - ballRadius, ballY - ballRadius, ballX + ballRadius, ballY + ballRadius);
ballColor.setColor(Color.RED);
canvas.drawOval(ballBounds, ballColor);
}
}
From the description of your intent, you should probably use OpenGL or a framework like libgdx which has physics and collision detection built in.
But to answer you question, you try this quick example:
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
import android.view.ViewTreeObserver;
public class BallView extends View{
// Ball attributes
private float ballRadius = 30;
private float ballX = 50;
private float ballY = 50;
private float ballSpeed = 10.0f;
private RectF ballBounds;
private Paint ballColor;
boolean doBallAnimation = false;
// For game elements
private int score = 0;
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
long startTime, prevTime; // Used to track elapsed time for animations and fps
public BallView(Context context){
super(context);
// Initialize game elements
ballBounds = new RectF();
ballColor = new Paint();
this.setFocusableInTouchMode(true);
getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener(){
#Override
public void onGlobalLayout(){
getViewTreeObserver().removeOnGlobalLayoutListener(this);
ballY = 0;
ballX = (getWidth()- ballRadius) / 2.0f;
doBallAnimation = true;
animator.start();
}
}
);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
#Override
public void onAnimationUpdate(ValueAnimator arg0){
long nowTime = System.currentTimeMillis();
float secs = (float)(nowTime - prevTime) / 1000f;
prevTime = nowTime;
if((ballY + ballSpeed) > (getHeight() - (ballRadius)))
{
animator.cancel();
return;
}
ballY += ballSpeed;
// Force a redraw to see the ball in its new position
invalidate();
}
});
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setDuration(3000);
}
public void onDraw(Canvas canvas){
// Draw ball
if(doBallAnimation)
{
ballBounds.set(ballX - ballRadius, ballY - ballRadius, ballX + ballRadius, ballY + ballRadius);
ballColor.setColor(Color.RED);
canvas.drawOval(ballBounds, ballColor);
}
}
}
I know its possible to create activities by doing something like the code bellow, where the view is not set from xml file but like this: setContentView(new myView(this));
What i don't understand is how to use this code but still have the ability to customize it, for instance if i wanted to add a button to the code bellow, how would i do it, because i cant simply add one to an xml layout can i?
ANY GOOD ANSWERS TO THIS WILL VERY MUCH APPRECIATED
thanks in advance!
package com.faceapp;
import android.app.Activity;
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.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;
public class FaceappActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
setContentView(new myView(this));
}
private class myView extends View{
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
// TODO Auto-generated constructor stub
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face5,
BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for(int i=0; i < numberOfFaceDetected; i++)
{
Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
canvas.drawRect(
(int)(myMidPoint.x - myEyesDistance),
(int)(myMidPoint.y - myEyesDistance),
(int)(myMidPoint.x + myEyesDistance),
(int)(myMidPoint.y + myEyesDistance),
myPaint);
}
}
}
}
^^^^^^^^^^^^^^^
Answered
How to position the button and imageview? (Ideally using relative layout)
The picture bellow shows you what i mean:
(Ignore that the image is re-sized)
NEW CODE:
package com.test;
import android.app.Activity;
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.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class TesttActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
Button button = new Button(this);
button.setText("Button!");
layout.addView(button);
myView custom = new myView(this);
layout.addView(custom);
setContentView(layout);
}
private class myView extends View{
private int imageWidth, imageHeight;
private int numberOfFace = 5;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
int numberOfFaceDetected;
Bitmap myBitmap;
public myView(Context context) {
super(context);
// TODO Auto-generated constructor stub
BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.face5,
BitmapFactoryOptionsbfo);
imageWidth = myBitmap.getWidth();
imageHeight = myBitmap.getHeight();
myFace = new FaceDetector.Face[numberOfFace];
myFaceDetect = new FaceDetector(imageWidth, imageHeight, numberOfFace);
numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
canvas.drawBitmap(myBitmap, 0, 0, null);
Paint myPaint = new Paint();
myPaint.setColor(Color.GREEN);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setStrokeWidth(3);
for(int i=0; i < numberOfFaceDetected; i++)
{
Face face = myFace[i];
PointF myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
canvas.drawRect(
(int)(myMidPoint.x - myEyesDistance),
(int)(myMidPoint.y - myEyesDistance),
(int)(myMidPoint.x + myEyesDistance),
(int)(myMidPoint.y + myEyesDistance),
myPaint);
}
}
}
}
You can pass setContentView() any form of view, to be the root view of your layout. Below is a dynamically built LinearLayout with a Button and your myView.
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
// Define the LinearLayout's characteristics
layout.setGravity(Gravity.CENTER);
layout.setOrientation(LinearLayout.VERTICAL);
// Set generic layout parameters
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setText("Button!");
layout.addView(button, params); // Modify this
myView custom = new myView(this);
layout.addView(custom, params); // Of course, this too
setContentView(layout);
}
}
Understand that you can only add child views to your root view if you pass setContentView() a ViewGroup; like RelativeLayout, LinearLayout, etc. In other words you cannot do this:
myView custom = new myView(this);
Button button = new Button(this);
button.setText("Button!");
custom.addView(button);
// Nope! Method "addView()" does not exist for a regular View...
setContentView(custom);
Also, naming convention suggests that each word in a class name should have the first letter capitalized. So myView ought to be MyView, at a minimum it makes your code easier to read for other programmers and the compiler will highlight your class variables with the correct color.
My custom view does not display entirely. Please see my screenshot:
And the source code
package com.dots;
import android.graphics.Color;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Dots1Activity extends Activity
{
private static final String TAG = "DotsActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
CustomDrawableView view1 = new CustomDrawableView(this, 50, 50, Constants.DOTS_RADIUS, Constants.DOTS_COLOR);
CustomDrawableView view2 = new CustomDrawableView(this, 150, 150, Constants.DOTS_RADIUS, Constants.DOTS_COLOR);
CustomDrawableView view3 = new CustomDrawableView(this, 300, 300, Constants.DOTS_RADIUS, Constants.DOTS_COLOR);
ll.addView(view1, layoutParams);
ll.addView(view2, layoutParams);
ll.addView(view3, layoutParams);
setContentView(ll);
}
}
class CustomDrawableView extends View implements View.OnClickListener{
private Context context;
private int x, y, radius, color;
public CustomDrawableView(Context context, int x, int y, int radius, int color) {
super(context);
this.context = context;
this.x = x;
this.y =y;
this.radius = radius;
this.color = color;
setOnClickListener(this);
}
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
canvas.drawCircle(x, y, radius, paint);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(View.MeasureSpec.makeMeasureSpec(Constants.DOTS_RADIUS*2, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(Constants.DOTS_RADIUS*2, View.MeasureSpec.EXACTLY));
}
public void onClick(View v) {
Toast.makeText(this.context,
x+"-"+y+"-"+radius,
Toast.LENGTH_SHORT).show();
}
}
public interface Constants
{
public static final int DOTS_RADIUS = 50;
public static final int DOTS_COLOR = Color.GREEN;
public static final int NUM_DOTS_ROWS = 5;
public static final int NUM_DOTS_COLS = 5;
public static final int WIDTH_BETWEEN_DOTS = 100;
public static final int HEIGHT_BETWEEN_DOTS = 100;
}
Making the assumption that you don't want the clipping you see in your screenshot. Your problem is that the values you return in onMeasure don't account for your x, y offsets:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(View.MeasureSpec.makeMeasureSpec(Constants.DOTS_RADIUS*2 + x, View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(Constants.DOTS_RADIUS*2 + y, View.MeasureSpec.EXACTLY));
}
What exactly do you want to Achieve? if you want to be fullscreen then use the FILL_PARENT flag instead of WRAP_CONTENT at least for the width of your view. also for the height there is a weight parameter that might help even the height of your view. but since its a custom drawing i cant help you further if there are any adjustments needed in your view code. you have to figure that out for yourself.
The radius of each of your "dots" is identical, and this directly translates into the answer you return in onMeasure(). You're changing the x and y location of the center, getting further from the actual View canvas.