Android: Starting intent from onClick on canvas - java

I recently started using a canvas over a layout because I could have animations in the background. However, I want to start a new activity after the user clicks a buttons. Here is the code so far...
public class GFX extends Activity implements View.OnTouchListener {
MyBringBack ourSurfaceView;
Paint title, play, options;
float x, y, sX, sY, fX, fY, dX, dY, aniX, aniY, scaledX, scaledY, changingRedX, changingYellowX, changingPurpleX, changingGreenX, whereIsRedXY, whereIsYellowXY, whereIsGreenXY, whereIsPurpleXY;
int whereIsRedY, redXThing, whereIsYellowY, whereIsGreenY, whereIsPurpleY, yellowXThing, greenXThing, purpleXThing, firstRun;
Bitmap green, yellow, red, purple, plus, redFixed, yellowFixed, greenFixed, purpleFixed, titleTest, playTest, playFixed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ourSurfaceView = new MyBringBack(this);
ourSurfaceView.setOnTouchListener(this);
x = 0;
y = 0;
sX = 0;
sY = 0;
fX = 0;
fY = 0;
Context ctx;
firstRun = 0;
dX = dY = aniX = aniY = scaledX = scaledY = redXThing = 0;
ctx = this;
green = BitmapFactory.decodeResource(getResources(), R.drawable.greenhairedpotatoblack);
yellow = BitmapFactory.decodeResource(getResources(), R.drawable.yellowhairedpotatoblack);
red = BitmapFactory.decodeResource(getResources(), R.drawable.redhairedpotatoblack);
purple = BitmapFactory.decodeResource(getResources(), R.drawable.purplehairedpotatoblack);
plus = BitmapFactory.decodeResource(getResources(), R.drawable.plus);
titleTest = BitmapFactory.decodeResource(getResources(), R.drawable.title);
playTest = BitmapFactory.decodeResource(getResources(), R.drawable.play);
setContentView(ourSurfaceView);
}
#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_gfx, menu);
return true;
}
#Override
protected void onPause() {
super.onPause();
ourSurfaceView.pause();
}
#Override
protected void onResume() {
super.onResume();
ourSurfaceView.resume();
}
#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);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
try {
Thread.sleep(1000/60);
} catch (InterruptedException e) {
e.printStackTrace();
}
x = event.getX();
y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
//if(y > play.getTextBounds("Play", );)
break;
}
return true;
}
public class MyBringBack extends SurfaceView implements Runnable {
SurfaceHolder ourHolder;
Thread ourThread = null;
boolean isRunning = false;
public MyBringBack(Context context) {
super(context);
ourHolder = getHolder();
}
public void pause(){
isRunning = false;
while(true){
try {
ourThread.join();
} catch (InterruptedException e){
e.printStackTrace();
}
break;
}
ourThread = null;
}
public void resume(){
isRunning = true;
ourThread = new Thread(this);
ourThread.start();
}
#Override
public void run() {
while(isRunning){
if(!ourHolder.getSurface().isValid())
continue;
Canvas canvas = ourHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
if(firstRun == 0){
changingRedX = 0 - red.getWidth();
yellowXThing = 1;
changingYellowX = canvas.getWidth();
greenXThing = 1;
firstRun = 1;
title = new Paint();
title.setColor(Color.parseColor("#0889ec"));
title.setTextSize(180);
title.setTextAlign(Paint.Align.CENTER);
title.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
play = new Paint();
play.setTextSize(140);
play.setColor(Color.WHITE);
play.setTextAlign(Paint.Align.CENTER);
options = new Paint();
options.setTextSize(140);
options.setColor(Color.WHITE);
options.setTextAlign(Paint.Align.CENTER);
playFixed = getResizedBitmap(playTest, canvas.getWidth()/5, canvas.getHeight()/3);
redFixed = getResizedBitmap(red, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (red.getHeight()/red.getWidth()));
yellowFixed = getResizedBitmap(yellow, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (yellow.getHeight()/yellow.getWidth()));
greenFixed = getResizedBitmap(green, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (green.getHeight()/green.getWidth()));
purpleFixed = getResizedBitmap(purple, canvas.getWidth()/6, (int)canvas.getWidth()/6 * (purple.getHeight()/purple.getWidth()));
}
if((x>(canvas.getWidth()/2)-(playFixed.getWidth()/2)&&(x<(canvas.getWidth()/2)-(playFixed.getWidth()/2) + playFixed.getWidth()))
&& ((y > 4*(canvas.getHeight()/9))&& (y<4*(canvas.getHeight()/9)+playFixed.getHeight()))){
**** HERE IS WHERE I WANT TO START THE NEW INTENT ****
}
if(whereIsRedY == 0){
whereIsRedXY = (int) (Math.random() * canvas.getHeight()) - 20;
whereIsRedY = 1;
}
if(whereIsYellowY == 0){
whereIsYellowXY = (int) (Math.random() * canvas.getHeight()) - 20;
whereIsYellowY = 1;
}
if(whereIsGreenY == 0){
whereIsGreenXY = (int) (Math.random() * canvas.getWidth()) - 20;
whereIsGreenY = 1;
}
if(whereIsPurpleY == 0){
whereIsPurpleXY = (int) (Math.random() * canvas.getWidth()) - 20;
whereIsPurpleY = 1;
}
if((changingRedX > canvas.getWidth() + redFixed.getWidth()) && redXThing == 0){
changingRedX = canvas.getWidth() + 3*(redFixed.getWidth());
whereIsRedY = 0;
redXThing = 1;
}
if((changingRedX < 0 - redFixed.getWidth()) && redXThing == 1){
changingRedX = 0 - 4*(redFixed.getWidth());
whereIsRedY = 0;
redXThing = 0;
}
if(redXThing == 0) {
changingRedX += 10;
}
if(redXThing == 1) {
changingRedX -= 10;
}
if((changingYellowX > canvas.getWidth() + yellowFixed.getWidth()) && yellowXThing == 0){
changingYellowX = canvas.getWidth() + 3*(yellowFixed.getWidth());
whereIsYellowY = 0;
yellowXThing = 1;
}
if((changingYellowX < 0 - yellowFixed.getWidth()) && yellowXThing == 1){
changingYellowX = 0 - 4*(yellowFixed.getWidth());
whereIsYellowY = 0;
yellowXThing = 0;
}
if(yellowXThing == 0) {
changingYellowX += 13;
}
if(yellowXThing == 1) {
changingYellowX -= 13;
}
if((changingGreenX > canvas.getHeight() + greenFixed.getHeight()) && greenXThing == 0){
changingGreenX = canvas.getHeight() + 3*(greenFixed.getHeight());
whereIsGreenY = 0;
greenXThing = 1;
}
if((changingGreenX < 0 - greenFixed.getHeight()) && greenXThing == 1){
changingGreenX = 0 - 4*(greenFixed.getHeight());
whereIsGreenY = 0;
greenXThing = 0;
}
if(greenXThing == 0) {
changingGreenX += 8;
}
if(greenXThing == 1) {
changingGreenX -= 8;
}
if((changingPurpleX > canvas.getHeight() + purpleFixed.getHeight()) && purpleXThing == 0){
changingPurpleX = canvas.getHeight() + 3*(purpleFixed.getHeight());
whereIsPurpleY = 0;
purpleXThing = 1;
}
if((changingPurpleX < 0 - purpleFixed.getHeight()) && purpleXThing == 1){
changingPurpleX = 0 - 4*(purpleFixed.getHeight());
whereIsPurpleY = 0;
purpleXThing = 0;
}
if(purpleXThing == 0) {
changingPurpleX += 15;
}
if(purpleXThing == 1) {
changingPurpleX -= 15;
}
canvas.drawBitmap(redFixed, changingRedX, whereIsRedXY, null);
canvas.drawBitmap(yellowFixed, changingYellowX, whereIsYellowXY, null);
canvas.drawBitmap(purpleFixed, whereIsPurpleXY, changingPurpleX, null);
canvas.drawBitmap(greenFixed, whereIsGreenXY, changingGreenX, null);
canvas.drawText("Mustache Me", (canvas.getWidth() ) / 2, (canvas.getHeight()/3), title);
//canvas.drawText("Play", canvas.getWidth()/2, canvas.getHeight()/2 + 40, play);
canvas.drawBitmap(playFixed, (canvas.getWidth()/2)-(playFixed.getWidth()/2), 4*(canvas.getHeight()/9), null);
canvas.drawText("Options", canvas.getWidth()/2, 2*(canvas.getHeight()/3), options);
ourHolder.unlockCanvasAndPost(canvas);
}
}
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
I labeled in my code where I want to intent to start, yet I keep getting the error: "Cannot resolve constructor Intetn(.....)"
The code I tried was this:
Intent i = new Intent(this, WhichGameActivity.class);
Thanks for any help :)
Cheers.

Use this:
new Intent(GFX.this,WhichGameActivity.class);
You can't just use this because you're inside a inner class, thus this belongs to the inner class context.

Pay attention to what Docs say about Intent constructor:
public Intent (Context packageContext, Class cls)
Create an intent for a specific component. ...
Parameters
packageContext A Context of the application package implementing this
class. cls The component class that is to be used for the
intent.
Your class MyBringBack is not a Context,so you can not use this code:
Intent i = new Intent(this, WhichGameActivity.class);
You have to store context that is received in constructor of MyBringBack as a field for example "myContext" and then use it in new Intent() like this:
Intent i = new Intent(myContext, WhichGameActivity.class);

Related

Unable to control volume and brightness of exoplayer

With help of some question i managed to add volume and brightness control to my video player with onTouchEvent method. But when i swipe up or down my app close(it Restarts). Any help on my code why am not able to control volume and brightness using onTouchEvent.
Here is my code:
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
tested_ok=false;
if (event.getX() < (sWidth / 2)) {
intLeft = true;
intRight = false;
} else if (event.getX() > (sWidth / 2)) {
intLeft = false;
intRight = true;
}
int upperLimit = (sHeight / 4) + 100;
int lowerLimit = ((sHeight / 4) * 3) - 150;
if (event.getY() < upperLimit) {
intBottom = false;
intTop = true;
} else if (event.getY() > lowerLimit) {
intBottom = true;
intTop = false;
} else {
intBottom = false;
intTop = false;
}
seekSpeed = (TimeUnit.MILLISECONDS.toSeconds(exoPlayer.getDuration()) * 0.1);
diffX = 0;
calculatedTime = 0;
seekDur = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(diffX) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(diffX)),
TimeUnit.MILLISECONDS.toSeconds(diffX) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(diffX)));
//TOUCH STARTED
baseX = event.getX();
baseY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
screen_swipe_move=true;
root.setVisibility(View.GONE);
diffX = (long) (Math.ceil(event.getX() - baseX));
diffY = (long) Math.ceil(event.getY() - baseY);
double brightnessSpeed = 0.05;
if (Math.abs(diffY) > MIN_DISTANCE) {
tested_ok = true;
}
if (Math.abs(diffY) > Math.abs(diffX)) {
if (intLeft) {
cResolver = getContentResolver();
window = getWindow();
try {
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
int new_brightness = (int) (brightness - (diffY * brightnessSpeed));
if (new_brightness > 250) {
new_brightness = 250;
} else if (new_brightness < 1) {
new_brightness = 1;
}
double brightPerc = Math.ceil((((double) new_brightness / (double) 250) * (double) 100));
brightnessBarContainer.setVisibility(View.VISIBLE);
brightness_center_text.setVisibility(View.VISIBLE);
brightnessBar.setProgress((int) brightPerc);
brigtness_perc_center_text.setText(" " + (int) brightPerc);
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, (new_brightness));
WindowManager.LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = brightness / (float) 255;
window.setAttributes(layoutpars);
}else if (intRight) {
vol_center_text.setVisibility(View.VISIBLE);
mediavolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
double cal = (double) diffY * ((double)maxVol/(double)(device_height*4));
int newMediaVolume = mediavolume - (int) cal;
if (newMediaVolume > maxVol) {
newMediaVolume = maxVol;
} else if (newMediaVolume < 1) {
newMediaVolume = 0;
}
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newMediaVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
double volPerc = Math.ceil((((double) newMediaVolume / (double) maxVol) * (double) 100));
vol_perc_center_text.setText(" " + (int) volPerc);
volumeBarContainer.setVisibility(View.VISIBLE);
volumeBar.setProgress((int) volPerc);
}
}else if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > (MIN_DISTANCE + 100)) {
}
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
screen_swipe_move=false;
tested_ok = false;
seekBar_center_text.setVisibility(View.GONE);
brightness_center_text.setVisibility(View.GONE);
vol_center_text.setVisibility(View.GONE);
brightnessBarContainer.setVisibility(View.GONE);
volumeBarContainer.setVisibility(View.GONE);
onlySeekbar.setVisibility(View.VISIBLE);
root.setVisibility(View.VISIBLE);
calculatedTime = (int) (exoPlayer.getCurrentPosition() + (calculatedTime));
exoPlayer.seekTo(calculatedTime);
break;
}
return super.onTouchEvent(event);
}
FYI: i can't make Log since i don't have emulator. your help would be more helpful thanks in advance.
Edit: when i swipe down on volume it move to zero, it doesn't reduce slowly and only the volume down works.
Here is complete code of VideoPlayerActivity.java
package com.sanoj.jlplayer.Activities;
public class VideoPlayerActivity extends AppCompatActivity {
Uri videoUri;
#BindView(R.id.playerView) PlayerView playerView;
#BindView(R.id.floating_widget) ImageView imageView;
#BindView(R.id.exoFullscreenIcon) ImageView imageView1;
#BindView(R.id.vol_perc_center_text) TextView vol_perc_center_text;
#BindView(R.id.brigtness_perc_center_text) TextView brigtness_perc_center_text;
#BindView(R.id.volume_slider) ProgressBar volumeBar;
#BindView(R.id.brightness_slider) ProgressBar brightnessBar;
#BindView(R.id.volume_slider_container) LinearLayout volumeBarContainer;
#BindView(R.id.brightness_slider_container) LinearLayout brightnessBarContainer;
#BindView(R.id.brightness_center_text) LinearLayout brightness_center_text;
#BindView(R.id.vol_center_text) LinearLayout vol_center_text;
#BindView(R.id.volIcon) ImageView volIcon;
#BindView(R.id.brightnessIcon) ImageView brightnessIcon;
#BindView(R.id.vol_image) ImageView vol_image;
#BindView(R.id.brightness_image) ImageView brightness_image;
boolean fullscreen = false;
ExoPlayer exoPlayer;
ExtractorsFactory extractorsFactory;
int sWidth,sHeight;
float baseX, baseY;
long diffX, diffY;
int calculatedTime;
String seekDur;
Boolean tested_ok = false;
Boolean screen_swipe_move = false;
boolean immersiveMode, intLeft, intRight, intTop, intBottom, finLeft, finRight, finTop, finBottom;
static final int MIN_DISTANCE = 150;
ContentResolver cResolver;
Window window;
TextView txt_seek_secs,txt_seek_currTime;
int brightness, mediavolume,device_height,device_width;
AudioManager audioManager;
double seekSpeed = 0;
LinearLayout root, seekBar_center_text, onlySeekbar;
Point size;
Display display;
SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
ButterKnife.bind(this);
Intent intent = getIntent();
//audio and brightness
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
display = getWindowManager().getDefaultDisplay();
size = new Point();
display.getSize(size);
sWidth = size.x;
sHeight = size.y;
if (intent!=null){
String uri_str = intent.getStringExtra("videoUri");
videoUri = Uri.parse(uri_str);
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
exoPlayer.setPlayWhenReady(false);
exoPlayer.release();
Intent serviceIntent = new Intent(VideoPlayerActivity.this,FloatingWidgetService.class);
serviceIntent.putExtra("videoUri",videoUri.toString());
startService(serviceIntent);
}
});
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
exoPlayer = ExoPlayerFactory.newSimpleInstance(this,trackSelector);
extractorsFactory = new DefaultExtractorsFactory();
playVideo();
}
private void playVideo() {
try {
String playerInfo = Util.getUserAgent(this,"VideoPlayer");
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this,playerInfo);
MediaSource mediaSource = new ExtractorMediaSource(videoUri,dataSourceFactory,extractorsFactory,null,null);
playerView.setPlayer(exoPlayer);
exoPlayer.prepare(mediaSource);
exoPlayer.setPlayWhenReady(true);
}catch (Exception e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
exoPlayer.setPlayWhenReady(false);
}
#Override
public void onBackPressed() {
super.onBackPressed();
exoPlayer.setPlayWhenReady(false);
exoPlayer.release();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
tested_ok=false;
if (event.getX() < (sWidth / 2)) {
intLeft = true;
intRight = false;
} else if (event.getX() > (sWidth / 2)) {
intLeft = false;
intRight = true;
}
int upperLimit = (sHeight / 4) + 100;
int lowerLimit = ((sHeight / 4) * 3) - 150;
if (event.getY() < upperLimit) {
intBottom = false;
intTop = true;
} else if (event.getY() > lowerLimit) {
intBottom = true;
intTop = false;
} else {
intBottom = false;
intTop = false;
}
seekSpeed = (TimeUnit.MILLISECONDS.toSeconds(exoPlayer.getDuration()) * 0.1);
diffX = 0;
calculatedTime = 0;
seekDur = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(diffX) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(diffX)),
TimeUnit.MILLISECONDS.toSeconds(diffX) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(diffX)));
//TOUCH STARTED
baseX = event.getX();
baseY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
screen_swipe_move=true;
root.setVisibility(View.GONE);
diffX = (long) (Math.ceil(event.getX() - baseX));
diffY = (long) Math.ceil(event.getY() - baseY);
double brightnessSpeed = 0.05;
if (Math.abs(diffY) > MIN_DISTANCE) {
tested_ok = true;
}
if (Math.abs(diffY) > Math.abs(diffX)) {
if (intLeft) {
cResolver = getContentResolver();
window = getWindow();
try {
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
int new_brightness = (int) (brightness - (diffY * brightnessSpeed));
if (new_brightness > 250) {
new_brightness = 250;
} else if (new_brightness < 1) {
new_brightness = 1;
}
double brightPerc = Math.ceil((((double) new_brightness / (double) 250) * (double) 100));
brightnessBarContainer.setVisibility(View.VISIBLE);
brightness_center_text.setVisibility(View.VISIBLE);
brightnessBar.setProgress((int) brightPerc);
if (brightPerc < 30) {
brightnessIcon.setImageResource(R.drawable.ic_bright_min);
brightness_image.setImageResource(R.drawable.ic_bright_min);
} else if (brightPerc > 30 && brightPerc < 80) {
brightnessIcon.setImageResource(R.drawable.ic_bright_med);
brightness_image.setImageResource(R.drawable.ic_bright_med);
} else if (brightPerc > 80) {
brightnessIcon.setImageResource(R.drawable.ic_bright_max);
brightness_image.setImageResource(R.drawable.ic_bright_max);
}
brigtness_perc_center_text.setText(" " + (int) brightPerc);
Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, (new_brightness));
WindowManager.LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = brightness / (float) 255;
window.setAttributes(layoutpars);
}else if (intRight) {
vol_center_text.setVisibility(View.VISIBLE);
mediavolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVol = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
double cal = (double) diffY * ((double)maxVol/(double)(device_height*4));
int newMediaVolume = mediavolume - (int) cal;
if (newMediaVolume > maxVol) {
newMediaVolume = maxVol;
} else if (newMediaVolume < 1) {
newMediaVolume = 0;
}
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, newMediaVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
double volPerc = Math.ceil((((double) newMediaVolume / (double) maxVol) * (double) 100));
vol_perc_center_text.setText(" " + (int) volPerc);
if (volPerc < 1) {
volIcon.setImageResource(R.drawable.ic_volume_mute);
vol_image.setImageResource(R.drawable.ic_volume_mute);
vol_perc_center_text.setVisibility(View.GONE);
} else if (volPerc >= 1) {
volIcon.setImageResource(R.drawable.ic_volume);
vol_image.setImageResource(R.drawable.ic_volume);
vol_perc_center_text.setVisibility(View.VISIBLE);
}
volumeBarContainer.setVisibility(View.VISIBLE);
volumeBar.setProgress((int) volPerc);
}
}else if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > (MIN_DISTANCE + 100)) {
tested_ok = true;
root.setVisibility(View.VISIBLE);
seekBar_center_text.setVisibility(View.VISIBLE);
onlySeekbar.setVisibility(View.VISIBLE);
(exoPlayer.getCurrentPosition() + (calculatedTime)));
}
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
screen_swipe_move=false;
tested_ok = false;
seekBar_center_text.setVisibility(View.GONE);
brightness_center_text.setVisibility(View.GONE);
vol_center_text.setVisibility(View.GONE);
brightnessBarContainer.setVisibility(View.GONE);
volumeBarContainer.setVisibility(View.GONE);
onlySeekbar.setVisibility(View.VISIBLE);
root.setVisibility(View.VISIBLE);
calculatedTime = (int) (exoPlayer.getCurrentPosition() + (calculatedTime));
exoPlayer.seekTo(calculatedTime);
break;
}
return super.onTouchEvent(event);
}
}
to control brightness and volume by touch i managed to find https://github.com/moneytoo/Player which let me to do the function with more feature and uses the exoplayer library
and easy to build as same as exoplayer.

Trouble getting order of Image Bitmap layers in Android correct

I have a piece of code that compares to images and places a marker on the difference. So far it works well, except the latest marker layer that is added always shows underneath all the older markers. I have the latest one as a yellow color and the older ones as red. When the difference is close to one of the red markers, the yellow marker shows behind those ones.
Is there anyone that can help me get the yellow (Latest marker) to appear on top?
This is my code so far:
public class CheckmarkActivity extends AppCompatActivity implements ZoomLayout.OnZoomableLayoutClickEventListener {
TextView tv;
RelativeLayout relativeLayout_work;
ImageView imageViewtest;
Bitmap prevBmp = null;
Timer t;
TimerTask task;
int time = 100;
float image_Width;
float image_Height;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkmark);
if (getResources().getBoolean(R.bool.is_tablet)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
tv = findViewById(R.id.tv);
relativeLayout_work = findViewById(R.id.relativeLayout_work);
imageViewtest = findViewById(R.id.imageViewtest);
prevBmp = ViewcontrollerActivity.workSession.getLastScreenShot();
if (prevBmp == null || ViewcontrollerActivity.workSession.workScreenShot == null) {
setResult(Activity.RESULT_CANCELED);
finish();
}
startTimer();
}
// image compare
class TestAsync extends AsyncTask<Object, Integer, String>
{
String TAG = getClass().getSimpleName();
PointF p;
Bitmap test_3;
protected void onPreExecute (){
super.onPreExecute();
Log.d(TAG + " PreExceute","On pre Exceute......");
}
protected String doInBackground(Object...arg0) {
test_3 = ImageHelper.findDifference(CheckmarkActivity.this, prevBmp, ViewcontrollerActivity.workSession.workScreenShot);
p = ImageHelper.findShot(test_3);
time = 1;
return "You are at PostExecute";
}
protected void onProgressUpdate(Integer...a){
super.onProgressUpdate(a);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
addImageToImageview();
PointF np = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
tv.setX(np.x - tv.getWidth() / 2);
tv.setY(np.y - tv.getHeight() / 2);
tv.setVisibility(View.VISIBLE);
// imageViewtest.setImageBitmap(test_3);
}
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i("OpenCV", "OpenCV loaded successfully");
new TestAsync().execute();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
#Override
protected void onResume() {
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d("OpenCV", "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d("OpenCV", "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public static int[] getBitmapOffset(ImageView img, Boolean includeLayout) {
int[] offset = new int[2];
float[] values = new float[9];
Matrix m = img.getImageMatrix();
m.getValues(values);
offset[0] = (int) values[5];
offset[1] = (int) values[2];
if (includeLayout) {
ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) img.getLayoutParams();
int paddingTop = (int) (img.getPaddingTop() );
int paddingLeft = (int) (img.getPaddingLeft() );
offset[0] += paddingTop + lp.topMargin;
offset[1] += paddingLeft + lp.leftMargin;
}
return offset;
}
public static int[] getBitmapPositionInsideImageView(ImageView imageView) {
int[] ret = new int[4];
if (imageView == null || imageView.getDrawable() == null)
return ret;
// Get image dimensions
// Get image matrix values and place them in an array
float[] f = new float[9];
imageView.getImageMatrix().getValues(f);
// Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
// Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
final Drawable d = imageView.getDrawable();
final int origW = d.getIntrinsicWidth();
final int origH = d.getIntrinsicHeight();
// Calculate the actual dimensions
final int actW = Math.round(origW * scaleX);
final int actH = Math.round(origH * scaleY);
ret[2] = actW;
ret[3] = actH;
// Get image position
// We assume that the image is centered into ImageView
int imgViewW = imageView.getWidth();
int imgViewH = imageView.getHeight();
int top = (int) (imgViewH - actH)/2;
int left = (int) (imgViewW - actW)/2;
ret[0] = left;
ret[1] = top;
return ret;
}
private void addImageToImageview(){
if (ViewcontrollerActivity.workSession.workScreenShot != null) {
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
Log.d("width", String.valueOf(imageViewtest.getWidth()));
}
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
for (int i = 0; i < ViewcontrollerActivity.workSession.getShotCount(); i++) {
PointF p = ViewcontrollerActivity.workSession.getPoint(i);
TextView t = new TextView(this);
t.setText("" + (i + 1));
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams((int)px, (int)px);
relativeLayout_work.addView(t);
t.setLayoutParams(param);
t.setGravity(Gravity.CENTER);
t.setBackgroundResource(R.drawable.circle);
p = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
t.setX(p.x);
t.setY(p.y);
t.setTag(10000 + i);
}
}
public void onConfirm(View v){
View vv = findViewById(R.id.relativeLayout_work);
PointF bp = Session.convertPointView2Bitmap(new PointF(tv.getX(), tv.getY()), relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
ViewcontrollerActivity.workSession.addNewShot(ViewcontrollerActivity.workSession.workScreenShot, bp);
setResult(Activity.RESULT_OK);
finish();
}
public void onCancel(View v){
setResult(Activity.RESULT_CANCELED);
finish();
}
#Override
public void onBackPressed() {
setResult(Activity.RESULT_CANCELED);
finish();
}
#Override
public void OnContentClickEvent(int action, float xR, float yR) {
int[] offset = new int[2];
int[] rect = new int[4];
offset = this.getBitmapOffset(imageViewtest, false);
int original_width = imageViewtest.getDrawable().getIntrinsicWidth();
int original_height = imageViewtest.getDrawable().getIntrinsicHeight();
rect = getBitmapPositionInsideImageView(imageViewtest);
Log.i("OffsetY", String.valueOf(offset[0]));
Log.i("OffsetX", String.valueOf(offset[1]));
Log.i( "0", String.valueOf(rect[0]));
Log.i( "1", String.valueOf(rect[1]));
Log.i( "2", String.valueOf(rect[2]));
Log.i( "3", String.valueOf(rect[3]));
if (xR > rect[0] && xR < rect[0] + rect[2] && yR > rect[1] && yR < rect[1] + rect[3]) {
tv.setX(xR - tv.getWidth() / 2);
tv.setY(yR - tv.getHeight() / 2);
}
// tv.setX(xR - tv.getWidth() / 2);
// tv.setY(yR - tv.getHeight() / 2);
}
public void onMoveButtonPressed(View v) {
ImageButton b = (ImageButton)v;
int mId = b.getId();
switch (mId) {
case R.id.imageButtonL:
tv.setX(tv.getX() - 1);
break;
case R.id.imageButtonR:
tv.setX(tv.getX() + 1);
break;
case R.id.imageButtonD:
tv.setY(tv.getY() + 1);
break;
case R.id.imageButtonU:
tv.setY(tv.getY() - 1);
break;
}
}
//timer change image
public void startTimer(){
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (time == 1){
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
// tv.setVisibility(View.VISIBLE);
tv.setText("" + (ViewcontrollerActivity.workSession.getShotCount() + 1));
t.cancel();
return;
}
if (time % 2 == 0) {
imageViewtest.setImageBitmap(prevBmp);
}
else if(time % 2 == 1){
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
}
time --;
}
});
}
};
t.scheduleAtFixedRate(task, 0, 500);
}
}
You can give the z-order of the child view with addView() function.
void addView (View child, int index)
ex)
private void addImageToImageview(){
if (ViewcontrollerActivity.workSession.workScreenShot != null) {
imageViewtest.setImageBitmap(ViewcontrollerActivity.workSession.workScreenShot);
Log.d("width", String.valueOf(imageViewtest.getWidth()));
}
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics());
int currChildrenCount = relativeLayout_work.getChildCount();
for (int i = 0; i < ViewcontrollerActivity.workSession.getShotCount(); i++) {
PointF p = ViewcontrollerActivity.workSession.getPoint(i);
TextView t = new TextView(this);
t.setText("" + (i + 1));
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams((int)px, (int)px);
relativeLayout_work.addView(t, currChildrenCount+i); // You can control the order like this
t.setLayoutParams(param);
t.setGravity(Gravity.CENTER);
t.setBackgroundResource(R.drawable.circle);
p = Session.convertPointBitmap2View(p, relativeLayout_work, ViewcontrollerActivity.workSession.workScreenShot);
t.setX(p.x);
t.setY(p.y);
t.setTag(10000 + i);
}
}

Setter/Getter method not working

Hi I am having a problem accessing variables/methods in my view class from my main activity. I just need to return the turns int from GameView.java and be able to access it in MainActivity and then insert it into my database. I try to use GameView mGameView = new GameView(getApplicationContext()); but this doesn't work and I can't access any methods from GameView with this.
My GameView class:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
int turns = 0;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
int cellContent;
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
}
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
turns++;
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getTurns() {
return turns;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
GameView mGameView = new GameView(getApplicationContext());
this.turns = mGameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void AddData() {
boolean isInserted = myDb.insertData(Integer.toString(turns));
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
}
In MainAcivity, inside setTurns()
Replace this
this.turns = mGameView.turns; //you can't access this variable directly
with
this.turns = mGameView.getTurns(); // Calling the public method getTurns()
please see this answer for explanation about Access modifiers in Java
There are two ways to fix this.
1. Preferred way:
Add a new Method in GameView class
public int getTurns() {
return turns;
}
And use this method where you want to access turns like:
this.turns = mGameView.getTurns();
2. Bad way:
Make turns variable public.

error on Method in android program

i have downloaded a android game program from internet and i tried to run it gives error on Method and goto statement.
i know goto statement is not support in java..
i dont know they are any other tool or language .
i want to know which technology or tool or language they are used.
this is the code
package com.infraredpixel.drop.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.*;
import android.util.Log;
import android.view.*;
import com.infraredpixel.drop.*;
import java.lang.reflect.Method;
import java.util.List;
// Referenced classes of package com.infraredpixel.drop.activities:
// ProfilingActivity, DebugActivity, MainMenuActivity
public class OpenGLDropActivity extends Activity
{
public OpenGLDropActivity()
{
}
private int getDefaultRotation()
{
int i;
WindowManager windowmanager;
Method amethod[];
String s;
int j;
i = 0;
windowmanager = (WindowManager)getSystemService("window");
amethod = windowmanager.getDefaultDisplay().getClass().getDeclaredMethods();
s = new String("getRotation");
j = amethod.length;
_L2:
Method method = null;
Display display;
if(i < j)
{
label0:
{
Method method1 = amethod[i];
Log.d("Methods", method1.getName());
if(!method1.getName().equals(s))
break label0;
method = method1;
}
}
display = windowmanager.getDefaultDisplay();
if(method != null)
{
int k;
try
{
k = ((Integer)method.invoke(display, new Object[0])).intValue();
}
catch(Exception exception)
{
return 0;
}
return k;
} else
{
return display.getOrientation();
}
i++;
if(true){ goto _L2;} else{ goto _L1;}
_L1:
}
protected void handleScore()
{
int i;
int j;
SharedPreferences sharedpreferences;
int k;
String s;
i = (int)(0.49F + (float)_StatusManager.dropDist());
j = (int)(0.49F + (float)_StatusManager.getStars());
sharedpreferences = getSharedPreferences("DropSettings", 0);
k = sharedpreferences.getInt("highScore", -1);
s = "";
if(2 != _ControlMode) goto _L2; else goto _L1;
_L1:
s = "tiltHighScore";
_L4:
int l = sharedpreferences.getInt(s, 0);
if(i + j > k && i + j > l)
{
_DeathDetector.setCurrentHighScore(i + j);
android.content.SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("highScore", -1);
editor.putInt(s, i + j);
editor.commit();
}
return;
_L2:
if(1 == _ControlMode || _ControlMode == 0)
s = "touchHighScore";
if(true) goto _L4; else goto _L3
_L3:
}
public void onCreate(Bundle bundle)
{
SharedPreferences sharedpreferences;
super.onCreate(bundle);
sharedpreferences = getSharedPreferences("DropSettings", 0);
spriteRenderer = new GLRenderer(getApplicationContext());
int i = sharedpreferences.getInt("fullScreenWidth", 480);
widthPixels = i;
int j = sharedpreferences.getInt("fullScreenHeight", 640);
RectF rectf = new RectF(0.0F, j, i, 0.0F);
boolean flag = sharedpreferences.getBoolean("useVibration", true);
boolean flag1 = sharedpreferences.getBoolean("godMode", false);
int k = sharedpreferences.getInt("ballType", 0);
int l = Math.max(sharedpreferences.getInt("highScore", 0), Math.max(sharedpreferences.getInt("tiltHighScore", 0), sharedpreferences.getInt("touchHighScore", 0)));
_ControlMode = sharedpreferences.getInt("controlMode", 2);
boolean flag2 = sharedpreferences.getBoolean("testModeDropSettings", false);
boolean flag3 = sharedpreferences.getBoolean("testModeMainSettings", false);
DropSettingsGroup adropsettingsgroup[];
DropManager dropmanager;
Handler handler;
Runnable runnable;
boolean flag4;
boolean flag5;
boolean flag6;
Runnable runnable1;
int k1;
float f;
float f1;
float f2;
float f3;
float f4;
float f5;
if(flag2)
{
adropsettingsgroup = new DropSettingsGroup[1];
adropsettingsgroup[0] = new DropSettingsGroup();
adropsettingsgroup[0].scrollSpeed = -sharedpreferences.getInt("scrollSpeed", getResources().getInteger(0x7f010000));
adropsettingsgroup[0].platformHeight = sharedpreferences.getInt("platformHeight", getResources().getInteger(0x7f050006));
adropsettingsgroup[0].platformHoleWidth = 70;
adropsettingsgroup[0].yAccel = sharedpreferences.getInt("yAcceleration", getResources().getInteger(0x7f050001));
adropsettingsgroup[0].yMaxSpeed = sharedpreferences.getInt("yMaxSpeed", getResources().getInteger(0x7f050002));
adropsettingsgroup[0].yBounce = 0.7F;
adropsettingsgroup[0].xAccel = sharedpreferences.getInt("xAcceleration", getResources().getInteger(0x7f050003));
adropsettingsgroup[0].xMaxSpeed = sharedpreferences.getInt("xMaxSpeed", getResources().getInteger(0x7f050004));
adropsettingsgroup[0].xBounce = sharedpreferences.getFloat("xBounce", 0.5F);
adropsettingsgroup[0].duration = 20F;
adropsettingsgroup[0].transitionTiles = false;
} else
if(_ControlMode == 0 || _ControlMode == 1)
adropsettingsgroup = DropSettingsGroup.getTestSettingsA();
else
adropsettingsgroup = DropSettingsGroup.getTestSettingsB();
dropmanager = new DropManager(rectf, adropsettingsgroup);
_DropManager = dropmanager;
if(flag)
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, (Vibrator)getSystemService("vibrator"));
else
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, null);
_StatusManager = new StatusManager();
_StatusManager.init(spriteRenderer, getBaseContext(), (float)widthPixels / 320F, rectf);
_GameOverLayer = new GameOverLayer();
_GameOverLayer.init(spriteRenderer, rectf);
handler = new Handler();
runnable = new Runnable() {
public void run()
{
handleScore();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
_DeathDetector = new DeathDetector(rectf, _DropManager, _StatusManager, _GameOverLayer, handler, runnable);
_DeathDetector.setCurrentHighScore(l);
if(_ControlMode != 0) goto _L2; else goto _L1
_L1:
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
_L4:
if(flag3)
{
k1 = sharedpreferences.getInt("movingAverageValue", 10);
f = sharedpreferences.getFloat("sensorCutoffX", 5F);
f1 = sharedpreferences.getFloat("inAirBreak", 0.3F);
f2 = sharedpreferences.getFloat("inAirMemory", 0.08F);
f3 = sharedpreferences.getFloat("gameSpeed", 1.0F);
f4 = sharedpreferences.getFloat("tiltAccelFactor", 1.0F);
f5 = sharedpreferences.getFloat("tiltAccelDiffFactor", 1.0F);
MySensorEventListener.SENSOR_CUTOFF_X = f;
MySensorEventListener.kFilteringFactor = 1.0F / (float)k1;
MySensorEventListener.accelFactor = f4;
MySensorEventListener.diffFactor = f5;
ControlComponent.inAirMovementFactor = 1.0F - f1;
ControlComponent.inAirMemoryMovementFactor = f2;
DropManager.speed = f3;
}
flag4 = sharedpreferences.getBoolean("canUseDrawTexture", true);
flag5 = sharedpreferences.getBoolean("canUseVBO", true);
GLSprite.shouldUseDrawTexture = flag4;
spriteRenderer.setVertMode(flag5);
ProfileRecorder.sSingleton.resetAll();
_StatusManager.setBall(_DropManager.getBall());
_DropManager.getCollisionComponent().setStatusManager(_StatusManager);
_ControlComponent = _DropManager.getControlComponent();
spriteRenderer.endInit();
simulationRuntime = new MainLoop();
if(!flag1)
simulationRuntime.addGameObject(_DeathDetector);
simulationRuntime.addGameObject(_DropManager);
simulationRuntime.addGameObject(_StatusManager);
simulationRuntime.addGameObject(_GameOverLayer);
setContentView(0x7f030001);
flag6 = sharedpreferences.getBoolean("glSafeMode", false);
mGLSurfaceView = (GLSurfaceView)findViewById(0x7f08001f);
mGLSurfaceView.setRenderer(spriteRenderer);
mGLSurfaceView.setEvent(simulationRuntime);
mGLSurfaceView.setSafeMode(flag6);
runnable1 = new Runnable() {
public void run()
{
android.content.SharedPreferences.Editor editor = getSharedPreferences("DropSettings", 0).edit();
editor.putString("testError", mGLSurfaceView.getLastError());
editor.commit();
Intent intent = new Intent(getApplicationContext(), com/infraredpixel/drop/activities/MainMenuActivity);
intent.putExtra("justCrashed", true);
startActivity(intent);
finish();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
mGLSurfaceView.setErrorMethod(runnable1);
sResetFlag = false;
Runtime.getRuntime().gc();
return;
_L2:
if(_ControlMode == 1)
{
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
} else
if(_ControlMode == 2)
{
mWakeLock = ((PowerManager)getSystemService("power")).newWakeLock(10, "Drop");
mWakeLock.acquire();
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i1 = list.size();
Sensor sensor = null;
if(i1 > 0)
sensor = (Sensor)list.get(0);
int j1 = getDefaultRotation();
MySensorEventListener mysensoreventlistener = new MySensorEventListener(_DropManager, _DeathDetector, j1);
_MyMotionListener = mysensoreventlistener;
sensormanager.registerListener(_MyMotionListener, sensor, 1);
MySensorEventListener.SENSOR_CUTOFF_X = 8.3F + 4.5F * (1.0F - sharedpreferences.getFloat("tiltSensitivity", 0.3F));
MySensorEventListener.kFilteringFactor = 1.0F;
ControlComponent.inAirMovementFactor = 1.0F;
ControlComponent.inAirMemoryMovementFactor = 0.0F;
DropManager.speed = 1.0F;
MySensorEventListener.accelFactor = 1.0F;
MySensorEventListener.diffFactor = 2.0F;
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onCreateOptionsMenu(Menu menu)
{
if(!TESTING)
{
return super.onCreateOptionsMenu(menu);
} else
{
menu.add(0, 1, 0, "profile");
menu.add(0, 2, 0, "debug/test");
menu.add(0, 3, 0, "main menu");
menu.add(0, 4, 0, "pause/resume");
return true;
}
}
protected void onDestroy()
{
if(mWakeLock != null && mWakeLock.isHeld())
{
mWakeLock.release();
mWakeLock = null;
}
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
{
sensormanager.unregisterListener(_MyMotionListener);
_MyMotionListener = null;
}
mGLSurfaceView = null;
_DropManager = null;
_StatusManager = null;
_DeathDetector = null;
_GameOverLayer = null;
simulationRuntime = null;
_ControlComponent = null;
super.onDestroy();
}
public boolean onKeyDown(int i, KeyEvent keyevent)
{
if(_ControlMode == 1)
{
if(i == 82 || i == 21)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveLeft();
_LeftPressed = true;
return true;
}
if(i == 84 || i == 22)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveRight();
_RightPressed = true;
return true;
} else
{
return super.onKeyDown(i, keyevent);
}
} else
{
return super.onKeyDown(i, keyevent);
}
}
public boolean onKeyUp(int i, KeyEvent keyevent)
{
if(_ControlMode != 1)
break MISSING_BLOCK_LABEL_102;
if(i != 82 && i != 21) goto _L2; else goto _L1
_L1:
boolean flag;
_LeftPressed = false;
flag = true;
_L5:
if(!_LeftPressed && !_RightPressed)
_ControlComponent.stopMovement();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
if(flag)
return true;
else
return super.onKeyUp(i, keyevent);
_L2:
if(i == 84) goto _L4; else goto _L3
_L3:
flag = false;
if(i != 22) goto _L5; else goto _L4
_L4:
_RightPressed = false;
flag = true;
goto _L5
return super.onKeyUp(i, keyevent);
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
switch(menuitem.getItemId())
{
default:
return false;
case 1: // '\001'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/ProfilingActivity));
return true;
case 2: // '\002'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/DebugActivity));
return true;
case 3: // '\003'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/MainMenuActivity));
return true;
case 4: // '\004'
break;
}
if(simulationRuntime.isPaused())
{
simulationRuntime.unPause();
mGLSurfaceView.onResume();
} else
{
simulationRuntime.pause();
mGLSurfaceView.onPause();
}
return true;
}
protected void onPause()
{
mGLSurfaceView.onPause();
if(mWakeLock != null && mWakeLock.isHeld())
mWakeLock.release();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
sensormanager.unregisterListener(_MyMotionListener);
}
super.onPause();
}
protected void onResume()
{
mGLSurfaceView.onResume();
if(sResetFlag)
{
handleScore();
_DropManager.reset();
sResetFlag = false;
}
if(mWakeLock != null && !mWakeLock.isHeld())
mWakeLock.acquire();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i = list.size();
Sensor sensor = null;
if(i > 0)
sensor = (Sensor)list.get(0);
sensormanager.registerListener(_MyMotionListener, sensor, 1);
}
super.onResume();
}
protected void onStart()
{
super.onStart();
}
public boolean onTouchEvent(MotionEvent motionevent)
{
if(!_GameOverLayer.isEnabled()) goto _L2; else goto _L1
_L1:
boolean flag;
int k = motionevent.getAction();
flag = false;
if(k == 0)
{
_GameOverLayer.doNextStep();
flag = true;
}
_L4:
int i;
ControlComponent controlcomponent;
int j;
float f;
try
{
Thread.sleep(20L);
}
catch(InterruptedException interruptedexception)
{
interruptedexception.printStackTrace();
return flag;
}
return flag;
_L2:
i = _ControlMode;
flag = false;
if(i == 0)
{
controlcomponent = _ControlComponent;
flag = false;
if(controlcomponent != null)
{
j = motionevent.getAction();
f = motionevent.getX();
if(j == 2)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
flag = true;
} else
if(j == 0)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
flag = true;
} else
{
flag = false;
if(j == 1)
{
_ControlComponent.stopMovement();
flag = true;
}
}
}
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onTrackballEvent(MotionEvent motionevent)
{
if(_ControlMode == 1)
{
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
float f = motionevent.getX();
_ControlComponent.autoBreak = true;
_ControlComponent.moveSideways(3.5F * f);
return true;
} else
{
return super.onTrackballEvent(motionevent);
}
}
public static final int CONTROL_MODE_KEYS = 1;
public static final int CONTROL_MODE_TILT = 2;
public static final int CONTROL_MODE_TOUCH = 0;
public static final String PREFS_NAME = "DropSettings";
private static boolean TESTING = false;
protected static boolean sResetFlag;
private ControlComponent _ControlComponent;
private int _ControlMode;
DeathDetector _DeathDetector;
DropManager _DropManager;
private GameOverLayer _GameOverLayer;
private boolean _LeftPressed;
MySensorEventListener _MyMotionListener;
private boolean _RightPressed;
StatusManager _StatusManager;
private GLSurfaceView mGLSurfaceView;
protected android.os.PowerManager.WakeLock mWakeLock;
MainLoop simulationRuntime;
private GLRenderer spriteRenderer;
private int widthPixels;
}
the program gives many error..
What you have here is not real Java, and you should not be using it as an example to learn Java programming from.
So what actually is this stuff?
It looks to me like someone has attempted to decompile an Android app, and the decompiler was unable to turn some of the code back into real Java. Instead, the decompiler has inserted goto "statements" in an attempt to convey the meaning of the code to the (human) reader.
This is obviously the output of a decompilation. While this is a good way to gain specific insight into programs, it's not beginner-level material just like #Jägermeister said, because jads lack the clarity and brevity of standard Java source code.
For example, the goto keyword is not supported on the source code side of the JDK, but it is used inside the byte code in the form of jump instructions. Breaks, continues, loops, ifs etc. may be turned into jumps in surjective ways. The decompiler cannot restore the original construct and resorts to just putting the gotos and labels in the jad. It's up to the programmer to restore reasonable, compilable flow constructs.
That said, the comprehensive answer to your question would be: it's java, but rather an image of the byte code stuff, not a strict restoration of the source code, and requires a manual touch-up to be compilable again.

How to animate Cards in android

How to animate Cards in android Card Game Like "Spades Free". My game is quite the same as crazy 8.i used android game development for dummies as a reference.but, i want to animate cards how can i do that.
public class GameView extends View {
private int screenW;
private int screenH;
private Context myContext;
private List<Card> deck = new ArrayList<Card>();
private int scaledCardW;
private int scaledCardH;
private Paint whitePaint;
private List<Card> myHand = new ArrayList<Card>();
private List<Card> oppHand = new ArrayList<Card>();
private int myScore = 0;
private int oppScore = 0;
private float scale;
private Bitmap cardBack;
private List<Card> discardPile = new ArrayList<Card>();
private boolean myTurn;
private ComputerPlayer computerPlayer = new ComputerPlayer();
private int movingCardIdx = -1;
private int movingX;
private int movingY;
private int validRank = 8;
private int validSuit = 0;
private Bitmap nextCardButton;
private int scoreThisHand = 0;
public GameView(Context context) {
super(context);
myContext = context;
scale = myContext.getResources().getDisplayMetrics().density;
whitePaint = new Paint();
whitePaint.setAntiAlias(true);
whitePaint.setColor(Color.WHITE);
whitePaint.setStyle(Paint.Style.STROKE);
whitePaint.setTextAlign(Paint.Align.LEFT);
whitePaint.setTextSize(scale*15);
}
#Override
public void onSizeChanged (int w, int h, int oldw, int oldh){
super.onSizeChanged(w, h, oldw, oldh);
screenW = w;
screenH = h;
Bitmap tempBitmap = BitmapFactory.decodeResource(myContext.getResources(), R.drawable.card_back);
scaledCardW = (int) (screenW/8);
scaledCardH = (int) (scaledCardW*1.28);
cardBack = Bitmap.createScaledBitmap(tempBitmap, scaledCardW, scaledCardH, false);
nextCardButton = BitmapFactory.decodeResource(getResources(), R.drawable.arrow_next);
initCards();
dealCards();
drawCard(discardPile);
validSuit = discardPile.get(0).getSuit();
validRank = discardPile.get(0).getRank();
myTurn = new Random().nextBoolean();
if (!myTurn) {
makeComputerPlay();
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawText("Computer Score: " + Integer.toString(oppScore), 10, whitePaint.getTextSize()+10, whitePaint);
canvas.drawText("My Score: " + Integer.toString(myScore), 10, screenH-whitePaint.getTextSize()-10, whitePaint);
for (int i = 0; i < oppHand.size(); i++) {
canvas.drawBitmap(cardBack,
i*(scale*5),
whitePaint.getTextSize()+(50*scale),
null);
}
canvas.drawBitmap(cardBack, (screenW/2)-cardBack.getWidth()-10, (screenH/2)-(cardBack.getHeight()/2), null);
if (!discardPile.isEmpty()) {
canvas.drawBitmap(discardPile.get(0).getBitmap(),
(screenW/2)+10,
(screenH/2)-(cardBack.getHeight()/2),
null);
}
if (myHand.size() > 7) {
canvas.drawBitmap(nextCardButton,
screenW-nextCardButton.getWidth()-(30*scale),
screenH-nextCardButton.getHeight()-scaledCardH-(90*scale),
null);
}
for (int i = 0; i < myHand.size(); i++) {
if (i == movingCardIdx) {
canvas.drawBitmap(myHand.get(i).getBitmap(),
movingX,
movingY,
null);
} else {
if (i < 7) {
canvas.drawBitmap(myHand.get(i).getBitmap(),
i*(scaledCardW+5),
screenH-scaledCardH-whitePaint.getTextSize()-(50*scale),
null);
}
}
}
invalidate();
}
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
int X = (int)event.getX();
int Y = (int)event.getY();
switch (eventaction ) {
case MotionEvent.ACTION_DOWN:
if (myTurn) {
for (int i = 0; i < 7; i++) {
if (X > i*(scaledCardW+5) && X < i*(scaledCardW+5) + scaledCardW &&
Y > screenH-scaledCardH-whitePaint.getTextSize()-(50*scale)) {
movingCardIdx = i;
movingX = X-(int)(30*scale);
movingY = Y-(int)(70*scale);
}
}
}
break;
case MotionEvent.ACTION_MOVE:
movingX = X-(int)(30*scale);
movingY = Y-(int)(70*scale);
break;
case MotionEvent.ACTION_UP:
if (movingCardIdx > -1 &&
X > (screenW/2)-(100*scale) &&
X < (screenW/2)+(100*scale) &&
Y > (screenH/2)-(100*scale) &&
Y < (screenH/2)+(100*scale) &&
(myHand.get(movingCardIdx).getRank() == 8 ||
myHand.get(movingCardIdx).getRank() == validRank ||
myHand.get(movingCardIdx).getSuit() == validSuit)) {
validRank = myHand.get(movingCardIdx).getRank();
validSuit = myHand.get(movingCardIdx).getSuit();
discardPile.add(0, myHand.get(movingCardIdx));
myHand.remove(movingCardIdx);
if (myHand.isEmpty()) {
endHand();
} else {
if (validRank == 8) {
showChooseSuitDialog();
} else {
myTurn = false;
makeComputerPlay();
}
}
}
if (movingCardIdx == -1 && myTurn &&
X > (screenW/2)-(100*scale) &&
X < (screenW/2)+(100*scale) &&
Y > (screenH/2)-(100*scale) &&
Y < (screenH/2)+(100*scale)) {
if (checkForValidDraw()) {
drawCard(myHand);
} else {
Toast.makeText(myContext, "You have a valid play.", Toast.LENGTH_SHORT).show();
}
}
if (myHand.size() > 7 &&
X > screenW-nextCardButton.getWidth()-(30*scale) &&
Y > screenH-nextCardButton.getHeight()-scaledCardH-(90*scale) &&
Y < screenH-nextCardButton.getHeight()-scaledCardH-(60*scale)) {
Collections.rotate(myHand, 1);
}
movingCardIdx = -1;
break;
}
invalidate();
return true;
}
private void showChooseSuitDialog() {
final Dialog chooseSuitDialog = new Dialog(myContext);
chooseSuitDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
chooseSuitDialog.setContentView(R.layout.choose_suit_dialog);
final Spinner suitSpinner = (Spinner) chooseSuitDialog.findViewById(R.id.suitSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
myContext, R.array.suits, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
suitSpinner.setAdapter(adapter);
Button okButton = (Button) chooseSuitDialog.findViewById(R.id.okButton);
okButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
validSuit = (suitSpinner.getSelectedItemPosition()+1)*100;
String suitText = "";
if (validSuit == 100) {
suitText = "Diamonds";
} else if (validSuit == 200) {
suitText = "Clubs";
} else if (validSuit == 300) {
suitText = "Hearts";
} else if (validSuit == 400) {
suitText = "Spades";
}
chooseSuitDialog.dismiss();
Toast.makeText(myContext, "You chose " + suitText, Toast.LENGTH_SHORT).show();
myTurn = false;
makeComputerPlay();
}
});
chooseSuitDialog.show();
}
private void initCards() {
for (int i = 0; i < 4; i++) {
for (int j = 102; j < 115; j++) {
int tempId = j + (i*100);
Card tempCard = new Card(tempId);
int resourceId = getResources().getIdentifier("card" + tempId, "drawable", myContext.getPackageName());
Bitmap tempBitmap = BitmapFactory.decodeResource(myContext.getResources(), resourceId);
scaledCardW = (int) (screenW/8);
scaledCardH = (int) (scaledCardW*1.28);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(tempBitmap, scaledCardW, scaledCardH, false);
tempCard.setBitmap(scaledBitmap);
deck.add(tempCard);
}
}
}
private void drawCard(List<Card> handToDraw) {
handToDraw.add(0, deck.get(0));
deck.remove(0);
if (deck.isEmpty()) {
for (int i = discardPile.size()-1; i > 0 ; i--) {
deck.add(discardPile.get(i));
discardPile.remove(i);
Collections.shuffle(deck,new Random());
}
}
}
private void dealCards() {
Collections.shuffle(deck,new Random());
for (int i = 0; i < 7; i++) {
drawCard(myHand);
drawCard(oppHand);
}
}
private boolean checkForValidDraw() {
boolean canDraw = true;
for (int i = 0; i < myHand.size(); i++) {
int tempId = myHand.get(i).getId();
int tempRank = myHand.get(i).getRank();
int tempSuit = myHand.get(i).getSuit();
if (validSuit == tempSuit || validRank == tempRank ||
tempId == 108 || tempId == 208 || tempId == 308 || tempId == 408) {
canDraw = false;
}
}
return canDraw;
}
private void makeComputerPlay() {
int tempPlay = 0;
while (tempPlay == 0) {
tempPlay = computerPlayer.makePlay(oppHand, validSuit, validRank);
if (tempPlay == 0) {
drawCard(oppHand);
}
}
if (tempPlay == 108 || tempPlay == 208 || tempPlay == 308 || tempPlay == 408) {
validRank = 8;
validSuit = computerPlayer.chooseSuit(oppHand);
String suitText = "";
if (validSuit == 100) {
suitText = "Diamonds";
} else if (validSuit == 200) {
suitText = "Clubs";
} else if (validSuit == 300) {
suitText = "Hearts";
} else if (validSuit == 400) {
suitText = "Spades";
}
Toast.makeText(myContext, "Computer chose " + suitText, Toast.LENGTH_SHORT).show();
} else {
validSuit = Math.round((tempPlay/100) * 100);
validRank = tempPlay - validSuit;
}
for (int i = 0; i < oppHand.size(); i++) {
Card tempCard = oppHand.get(i);
if (tempPlay == tempCard.getId()) {
discardPile.add(0, oppHand.get(i));
oppHand.remove(i);
}
}
if (oppHand.isEmpty()) {
endHand();
}
myTurn = true;
}
}
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/pressed_center"
android:state_pressed="true" />
<item android:drawable="#drawable/unpressed_center" />
You should make draweble in same layout file for pres or not press version

Categories

Resources