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.
Related
actually I'm using this part of code but nothing shown in screen
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, elativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
And this is the activity codes
public class LaunchActivity extends Activity implements ActionBarLayout.ActionBarLayoutDelegate, NotificationCenter.NotificationCenterDelegate, DialogsActivity.DialogsActivityDelegate {
private boolean finished;
private String videoPath;
private String sendingText;
private ArrayList<Uri> photoPathsArray;
private ArrayList<String> documentsPathsArray;
private ArrayList<Uri> documentsUrisArray;
private String documentsMimeType;
private ArrayList<String> documentsOriginalPathsArray;
private ArrayList<TLRPC.User> contactsToSend;
private int currentConnectionState;
private static ArrayList<BaseFragment> mainFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> layerFragmentsStack = new ArrayList<>();
private static ArrayList<BaseFragment> rightFragmentsStack = new ArrayList<>();
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener;
private ActionBarLayout actionBarLayout;
private ActionBarLayout layersActionBarLayout;
private ActionBarLayout rightActionBarLayout;
private FrameLayout shadowTablet;
private FrameLayout shadowTabletSide;
private View backgroundTablet;
protected DrawerLayoutContainer drawerLayoutContainer;
private DrawerLayoutAdapter drawerLayoutAdapter;
private PasscodeView passcodeView;
private AlertDialog visibleDialog;
private RecyclerListView sideMenu;
private AlertDialog localeDialog;
private boolean loadingLocaleDialog;
private HashMap<String, String> systemLocaleStrings;
private HashMap<String, String> englishLocaleStrings;
private Intent passcodeSaveIntent;
private boolean passcodeSaveIntentIsNew;
private boolean passcodeSaveIntentIsRestore;
private boolean tabletFullSize;
private Runnable lockRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
ApplicationLoader.postInitApplication();
NativeCrashManager.handleDumpFiles(this);
AndroidUtilities.checkDisplaySize(this, getResources().getConfiguration());
Log.i(this.getClass().getName(), "onCreate: ");
if (!UserConfig.isClientActivated()) {
Intent intent = getIntent();
if (intent != null && intent.getAction() != null && (Intent.ACTION_SEND.equals(intent.getAction()) || intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE))) {
super.onCreate(savedInstanceState);
finish();
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
long crashed_time = preferences.getLong("intro_crashed_time", 0);
boolean fromIntro = intent.getBooleanExtra("fromIntro", false);
if (fromIntro) {
preferences.edit().putLong("intro_crashed_time", 0).commit();
}
if (Math.abs(crashed_time - System.currentTimeMillis()) >= 60 * 2 * 1000 && intent != null && !fromIntro) {
preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", MODE_PRIVATE);
Map<String, ?> state = preferences.getAll();
if (state.isEmpty()) {
Intent intent2 = new Intent(this, IntroActivity.class);
intent2.setData(intent.getData());
startActivity(intent2);
super.onCreate(savedInstanceState);
finish();
return;
}
}
}
requestWindowFeature(Window.FEATURE_NO_TITLE);
setTheme(R.style.Theme_TMessages);
getWindow().setBackgroundDrawableResource(R.drawable.transparent);
if (UserConfig.passcodeHash.length() > 0 && !UserConfig.allowScreenCapture) {
try {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
} catch (Exception e) {
FileLog.e(e);
}
}
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 24) {
AndroidUtilities.isInMultiwindow = isInMultiWindowMode();
}
Theme.createChatResources(this, false);
if (UserConfig.passcodeHash.length() != 0 && UserConfig.appLocked) {
UserConfig.lastPauseTime = ConnectionsManager.getInstance().getCurrentTime();
}
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
AndroidUtilities.statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
actionBarLayout = new ActionBarLayout(this);
drawerLayoutContainer = new DrawerLayoutContainer(this);
setContentView(drawerLayoutContainer, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
if (AndroidUtilities.isTablet()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
RelativeLayout launchLayout = new RelativeLayout(this) {
private boolean inLayout;
#Override
public void requestLayout() {
if (inLayout) {
return;
}
super.requestLayout();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
inLayout = true;
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(width, height);
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
tabletFullSize = false;
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTabletSide.measure(MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(1), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
rightActionBarLayout.measure(MeasureSpec.makeMeasureSpec(width - leftWidth, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
} else {
tabletFullSize = true;
actionBarLayout.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
}
backgroundTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
shadowTablet.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY));
layersActionBarLayout.measure(MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(530), width), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(Math.min(AndroidUtilities.dp(528), height), MeasureSpec.EXACTLY));
inLayout = false;
}
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int height = b - t;
if (!AndroidUtilities.isInMultiwindow && (!AndroidUtilities.isSmallTablet() || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
int leftWidth = width / 100 * 35;
if (leftWidth < AndroidUtilities.dp(320)) {
leftWidth = AndroidUtilities.dp(320);
}
shadowTabletSide.layout(leftWidth, 0, leftWidth + shadowTabletSide.getMeasuredWidth(), shadowTabletSide.getMeasuredHeight());
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
rightActionBarLayout.layout(leftWidth, 0, leftWidth + rightActionBarLayout.getMeasuredWidth(), rightActionBarLayout.getMeasuredHeight());
} else {
actionBarLayout.layout(0, 0, actionBarLayout.getMeasuredWidth(), actionBarLayout.getMeasuredHeight());
}
int x = (width - layersActionBarLayout.getMeasuredWidth()) / 2;
int y = (height - layersActionBarLayout.getMeasuredHeight()) / 2;
layersActionBarLayout.layout(x, y, x + layersActionBarLayout.getMeasuredWidth(), y + layersActionBarLayout.getMeasuredHeight());
backgroundTablet.layout(0, 0, backgroundTablet.getMeasuredWidth(), backgroundTablet.getMeasuredHeight());
shadowTablet.layout(0, 0, shadowTablet.getMeasuredWidth(), shadowTablet.getMeasuredHeight());
}
};
drawerLayoutContainer.addView(launchLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
backgroundTablet = new View(this);
//BitmapDrawable drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.catstile);
//drawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
backgroundTablet.setBackgroundResource(R.drawable.catstile);
launchLayout.addView(backgroundTablet, LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
launchLayout.addView(actionBarLayout);
rightActionBarLayout = new ActionBarLayout(this);
rightActionBarLayout.init(rightFragmentsStack);
rightActionBarLayout.setDelegate(this);
launchLayout.addView(rightActionBarLayout);
shadowTabletSide = new FrameLayout(this);
shadowTabletSide.setBackgroundColor(0x40295274);
launchLayout.addView(shadowTabletSide);
shadowTablet = new FrameLayout(this);
shadowTablet.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
shadowTablet.setBackgroundColor(0x7f000000);
launchLayout.addView(shadowTablet);
shadowTablet.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!actionBarLayout.fragmentsStack.isEmpty() && event.getAction() == MotionEvent.ACTION_UP) {
float x = event.getX();
float y = event.getY();
int location[] = new int[2];
layersActionBarLayout.getLocationOnScreen(location);
int viewX = location[0];
int viewY = location[1];
if (layersActionBarLayout.checkTransitionAnimation() || x > viewX && x < viewX + layersActionBarLayout.getWidth() && y > viewY && y < viewY + layersActionBarLayout.getHeight()) {
return false;
} else {
if (!layersActionBarLayout.fragmentsStack.isEmpty()) {
for (int a = 0; a < layersActionBarLayout.fragmentsStack.size() - 1; a++) {
layersActionBarLayout.removeFragmentFromStack(layersActionBarLayout.fragmentsStack.get(0));
a--;
}
layersActionBarLayout.closeLastFragment(true);
}
return true;
}
}
return false;
}
});
shadowTablet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
layersActionBarLayout = new ActionBarLayout(this);
layersActionBarLayout.setRemoveActionBarExtraHeight(true);
layersActionBarLayout.setBackgroundView(shadowTablet);
layersActionBarLayout.setUseAlphaAnimations(true);
layersActionBarLayout.setBackgroundResource(R.drawable.boxshadow);
layersActionBarLayout.init(layerFragmentsStack);
layersActionBarLayout.setDelegate(this);
layersActionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
layersActionBarLayout.setVisibility(layerFragmentsStack.isEmpty() ? View.GONE : View.VISIBLE);
launchLayout.addView(layersActionBarLayout);
// add single button for find near me
Button myButton = new Button(this);
myButton.setText("Press me");
myButton.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams buttonParams =
new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
buttonParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
launchLayout.addView(myButton,buttonParams);
setContentView(launchLayout);
} else {
drawerLayoutContainer.addView(actionBarLayout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
sideMenu = new RecyclerListView(this);
sideMenu.setBackgroundColor(Theme.getColor(Theme.key_chats_menuBackground));
sideMenu.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
sideMenu.setAdapter(drawerLayoutAdapter = new DrawerLayoutAdapter(this));
drawerLayoutContainer.setDrawerLayout(sideMenu);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) sideMenu.getLayoutParams();
Point screenSize = AndroidUtilities.getRealScreenSize();
layoutParams.width = AndroidUtilities.isTablet() ? AndroidUtilities.dp(320) : Math.min(AndroidUtilities.dp(320), Math.min(screenSize.x, screenSize.y) - AndroidUtilities.dp(56));
layoutParams.height = LayoutHelper.MATCH_PARENT;
sideMenu.setLayoutParams(layoutParams);
sideMenu.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
#Override
public void onItemClick(final View view, int position) {
int id = drawerLayoutAdapter.getId(position);
if (position == 0) {
Bundle args = new Bundle();
args.putInt("user_id", UserConfig.getClientUserId());
presentFragment(new ChatActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 2) {
if (!MessagesController.isFeatureEnabled("chat_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
presentFragment(new GroupCreateActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 3) {
Bundle args = new Bundle();
args.putBoolean("onlyUsers", true);
args.putBoolean("destroyAfterSelect", true);
args.putBoolean("createSecretChat", true);
args.putBoolean("allowBots", false);
presentFragment(new ContactsActivity(args));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 4) {
if (!MessagesController.isFeatureEnabled("broadcast_create", actionBarLayout.fragmentsStack.get(actionBarLayout.fragmentsStack.size() - 1))) {
return;
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
if (!BuildVars.DEBUG_VERSION && preferences.getBoolean("channel_intro", false)) {
Bundle args = new Bundle();
args.putInt("step", 0);
presentFragment(new ChannelCreateActivity(args));
} else {
presentFragment(new ChannelIntroActivity());
preferences.edit().putBoolean("channel_intro", true).commit();
}
drawerLayoutContainer.closeDrawer(false);
} else if (id == 6) {
presentFragment(new ContactsActivity(null));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 7) {
if (BuildVars.DEBUG_PRIVATE_VERSION) {
/*AlertDialog.Builder builder = new AlertDialog.Builder(LaunchActivity.this);
builder.setTopImage(R.drawable.permissions_contacts, 0xff35a8e0);
builder.setMessage(AndroidUtilities.replaceTags(LocaleController.getString("ContactsPermissionAlert", R.string.ContactsPermissionAlert)));
builder.setPositiveButton(LocaleController.getString("ContactsPermissionAlertContinue", R.string.ContactsPermissionAlertContinue), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(LocaleController.getString("ContactsPermissionAlertNotNow", R.string.ContactsPermissionAlertNotNow), null);
showAlertDialog(builder);*/
showLanguageAlert(true);
} else {
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, ContactsController.getInstance().getInviteText());
startActivityForResult(Intent.createChooser(intent, LocaleController.getString("InviteFriends", R.string.InviteFriends)), 500);
} catch (Exception e) {
FileLog.e(e);
}
drawerLayoutContainer.closeDrawer(false);
}
} else if (id == 8) {
presentFragment(new SettingsActivity());
drawerLayoutContainer.closeDrawer(false);
} else if (id == 9) {
Browser.openUrl(LaunchActivity.this, LocaleController.getString("TelegramFaqUrl", R.string.TelegramFaqUrl));
drawerLayoutContainer.closeDrawer(false);
} else if (id == 10) {
presentFragment(new CallLogActivity());
drawerLayoutContainer.closeDrawer(false);
}
}
});
drawerLayoutContainer.setParentActionBarLayout(actionBarLayout);
actionBarLayout.setDrawerLayoutContainer(drawerLayoutContainer);
actionBarLayout.init(mainFragmentsStack);
actionBarLayout.setDelegate(this);
Theme.loadWallpaper();
passcodeView = new PasscodeView(this);
drawerLayoutContainer.addView(passcodeView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
NotificationCenter.getInstance().postNotificationName(NotificationCenter.closeOtherAppActivities, this);
currentConnectionState = ConnectionsManager.getInstance().getConnectionState();
NotificationCenter.getInstance().addObserver(this, NotificationCenter.appDidLogout);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.mainUserInfoChanged);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.closeOtherAppActivities);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didUpdatedConnectionState);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.needShowAlert);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.wasUnableToFindCurrentLocation);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetNewWallpapper);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.didSetPasscode);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.reloadInterface);
NotificationCenter.getInstance().addObserver(this, NotificationCenter.suggestedLangpack);
if (actionBarLayout.fragmentsStack.isEmpty()) {
if (!UserConfig.isClientActivated()) {
actionBarLayout.addFragmentToStack(new LoginActivity());
drawerLayoutContainer.setAllowOpenDrawer(false, false);
} else {
DialogsActivity dialogsActivity = new DialogsActivity(null);
dialogsActivity.setSideMenu(sideMenu);
actionBarLayout.addFragmentToStack(dialogsActivity);
drawerLayoutContainer.setAllowOpenDrawer(true, false);
}
try {
if (savedInstanceState != null) {
String fragmentName = savedInstanceState.getString("fragment");
if (fragmentName != null) {
Bundle args = savedInstanceState.getBundle("args");
switch (fragmentName) {
case "chat":
if (args != null) {
ChatActivity chat = new ChatActivity(args);
if (actionBarLayout.addFragmentToStack(chat)) {
chat.restoreSelfArgs(savedInstanceState);
}
}
break;
case "settings": {
SettingsActivity settings = new SettingsActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
case "group":
if (args != null) {
GroupCreateFinalActivity group = new GroupCreateFinalActivity(args);
if (actionBarLayout.addFragmentToStack(group)) {
group.restoreSelfArgs(savedInstanceState);
}
}
break;
case "channel":
if (args != null) {
ChannelCreateActivity channel = new ChannelCreateActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "edit":
if (args != null) {
ChannelEditActivity channel = new ChannelEditActivity(args);
if (actionBarLayout.addFragmentToStack(channel)) {
channel.restoreSelfArgs(savedInstanceState);
}
}
break;
case "chat_profile":
if (args != null) {
ProfileActivity profile = new ProfileActivity(args);
if (actionBarLayout.addFragmentToStack(profile)) {
profile.restoreSelfArgs(savedInstanceState);
}
}
break;
case "wallpapers": {
WallpapersActivity settings = new WallpapersActivity();
actionBarLayout.addFragmentToStack(settings);
settings.restoreSelfArgs(savedInstanceState);
break;
}
}
}
}
} catch (Exception e) {
FileLog.e(e);
}
} else {
BaseFragment fragment = actionBarLayout.fragmentsStack.get(0);
if (fragment instanceof DialogsActivity) {
((DialogsActivity) fragment).setSideMenu(sideMenu);
}
boolean allowOpen = true;
if (AndroidUtilities.isTablet()) {
allowOpen = actionBarLayout.fragmentsStack.size() <= 1 && layersActionBarLayout.fragmentsStack.isEmpty();
if (layersActionBarLayout.fragmentsStack.size() == 1 && layersActionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
}
if (actionBarLayout.fragmentsStack.size() == 1 && actionBarLayout.fragmentsStack.get(0) instanceof LoginActivity) {
allowOpen = false;
}
drawerLayoutContainer.setAllowOpenDrawer(allowOpen, false);
}
checkLayout();
handleIntent(getIntent(), false, savedInstanceState != null, false);
try {
String os1 = Build.DISPLAY;
String os2 = Build.USER;
if (os1 != null) {
os1 = os1.toLowerCase();
} else {
os1 = "";
}
if (os2 != null) {
os2 = os1.toLowerCase();
} else {
os2 = "";
}
if (os1.contains("flyme") || os2.contains("flyme")) {
AndroidUtilities.incorrectDisplaySizeFix = true;
final View view = getWindow().getDecorView().getRootView();
view.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int height = view.getMeasuredHeight();
if (Build.VERSION.SDK_INT >= 21) {
height -= AndroidUtilities.statusBarHeight;
}
if (height > AndroidUtilities.dp(100) && height < AndroidUtilities.displaySize.y && height + AndroidUtilities.dp(100) > AndroidUtilities.displaySize.y) {
AndroidUtilities.displaySize.y = height;
FileLog.e("fix display size y to " + AndroidUtilities.displaySize.y);
}
}
});
}
} catch (Exception e) {
FileLog.e(e);
}
MediaController.getInstance().setBaseActivity(this, true);
}
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);
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
I have created one pull to refresh listview now when I scroll or pull little bit then I have to add header view.
here my custom listview class
package com.app.refreshableList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.app.xxxxxx.R;
import com.google.android.gms.internal.el;
public class RefreshableListView extends ListView {
Boolean isScrool = false;
private View mHeaderContainer = null;
private View mHeaderView = null;
private ImageView mArrow = null;
private ProgressBar mProgress = null;
private TextView mText = null;
private float mY = 0;
private float mHistoricalY = 0;
private int mHistoricalTop = 0;
private int mInitialHeight = 0;
private boolean mFlag = false;
private boolean mArrowUp = false;
private boolean mIsRefreshing = false;
private int mHeaderHeight = 0;
private OnRefreshListener mListener = null;
private static final int REFRESH = 0;
private static final int NORMAL = 1;
private static final int HEADER_HEIGHT_DP = 62;
private static final String TAG = RefreshableListView.class.getSimpleName();
private ListViewObserver mObserver;
private View mTrackedChild;
private int mTrackedChildPrevPosition;
private int mTrackedChildPrevTop;
OnTouchListener touch;
View vHeader;
#Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (mTrackedChild == null) {
if (getChildCount() > 0) {
mTrackedChild = getChildInTheMiddle();
mTrackedChildPrevTop = mTrackedChild.getTop();
mTrackedChildPrevPosition = getPositionForView(mTrackedChild);
}
} else {
boolean childIsSafeToTrack = mTrackedChild.getParent() == this
&& getPositionForView(mTrackedChild) == mTrackedChildPrevPosition;
if (childIsSafeToTrack) {
int top = mTrackedChild.getTop();
if (mObserver != null) {
float deltaY = top - mTrackedChildPrevTop;
mObserver.onScroll(deltaY);
}
mTrackedChildPrevTop = top;
} else {
mTrackedChild = null;
}
}
}
private View getChildInTheMiddle() {
return getChildAt(getChildCount() / 2);
}
public void setObserver(ListViewObserver observer) {
mObserver = observer;
}
public RefreshableListView(final Context context) {
super(context);
initialize();
}
public RefreshableListView(final Context context, final AttributeSet attrs) {
super(context, attrs);
initialize();
}
public RefreshableListView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
initialize();
}
public void setOnRefreshListener(final OnRefreshListener l) {
mListener = l;
}
#Override
public void setOnTouchListener(OnTouchListener l) {
// TODO Auto-generated method stub
super.setOnTouchListener(l);
}
public void completeRefreshing() {
mProgress.setVisibility(View.INVISIBLE);
mArrow.setVisibility(View.VISIBLE);
mHandler.sendMessage(mHandler.obtainMessage(NORMAL, mHeaderHeight, 0));
mIsRefreshing = false;
invalidateViews();
}
#Override
public boolean onInterceptTouchEvent(final MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mHandler.removeMessages(REFRESH);
mHandler.removeMessages(NORMAL);
mY = mHistoricalY = ev.getY();
if (mHeaderContainer.getLayoutParams() != null) {
mInitialHeight = mHeaderContainer.getLayoutParams().height;
}
break;
}
return super.onInterceptTouchEvent(ev);
}
#Override
public boolean onTouchEvent(final MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_MOVE:
mHistoricalTop = getChildAt(0).getTop();
break;
case MotionEvent.ACTION_UP:
if (!mIsRefreshing) {
if (mArrowUp) {
startRefreshing();
mHandler.sendMessage(mHandler.obtainMessage(REFRESH,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
} else {
if (getChildAt(0).getTop() == 0) {
mHandler.sendMessage(mHandler.obtainMessage(NORMAL,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
}
}
} else {
mHandler.sendMessage(mHandler.obtainMessage(REFRESH,
(int) (ev.getY() - mY) / 2 + mInitialHeight, 0));
}
mFlag = false;
break;
}
return super.onTouchEvent(ev);
}
#Override
public boolean dispatchTouchEvent(final MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_MOVE
&& getFirstVisiblePosition() == 0) {
float direction = ev.getY() - mHistoricalY;
int height = (int) (ev.getY() - mY) / 2 + mInitialHeight;
if (height < 0) {
height = 0;
}
float deltaY = Math.abs(mY - ev.getY());
ViewConfiguration config = ViewConfiguration.get(getContext());
if (deltaY > config.getScaledTouchSlop()) {
// Scrolling downward
if (direction > 0) {
// Refresh bar is extended if top pixel of the first item is
// visible
if (getChildAt(0) != null) {
if (getChildAt(0).getTop() == 0) {
if (mHistoricalTop < 0) {
// mY = ev.getY(); // TODO works without
// this?mHistoricalTop = 0;
}
// if (isScrool == true) {
//
// } else {
// isScrool = true;
// addHeaderView(vHeader);
//
// // Animation anim = AnimationUtils.loadAnimation(
// // getContext(), R.anim.bounce_animation);
// // startAnimation(anim);
//
// smoothScrollToPosition(getChildAt(0).getTop());
// // bottom_layout.setVisibility(View.VISIBLE);
// }
// Extends refresh bar
/*****
* commented by me on 10-09-2014
*/
setHeaderHeight(height);
// Stop list scroll to prevent the list from
// overscrolling
ev.setAction(MotionEvent.ACTION_CANCEL);
mFlag = false;
}
}
} else if (direction < 0) {
// Scrolling upward
// Refresh bar is shortened if top pixel of the first item
// is
// visible
if (getChildAt(0) != null) {
if (getChildAt(0).getTop() == 0) {
setHeaderHeight(height);
// If scroll reaches top of the list, list scroll is
// enabled
if (getChildAt(1) != null
&& getChildAt(1).getTop() <= 1 && !mFlag) {
ev.setAction(MotionEvent.ACTION_DOWN);
mFlag = true;
}
}
}
}
}
mHistoricalY = ev.getY();
}
try {
return super.dispatchTouchEvent(ev);
} catch (Exception e) {
return false;
}
}
#Override
public boolean performItemClick(final View view, final int position,
final long id) {
if (position == 0) {
// This is the refresh header element
return true;
} else {
return super.performItemClick(view, position - 1, id);
}
}
private void initialize() {
LayoutInflater inflator = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vHeader = inflator.inflate(R.layout.search_header, null);
LayoutInflater inflater = (LayoutInflater) getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mHeaderContainer = inflater.inflate(R.layout.refreshable_list_header,
null);
mHeaderView = mHeaderContainer
.findViewById(R.id.refreshable_list_header);
mArrow = (ImageView) mHeaderContainer
.findViewById(R.id.refreshable_list_arrow);
mProgress = (ProgressBar) mHeaderContainer
.findViewById(R.id.refreshable_list_progress);
mText = (TextView) mHeaderContainer
.findViewById(R.id.refreshable_list_text);
addHeaderView(mHeaderContainer);
mHeaderHeight = (int) (HEADER_HEIGHT_DP * getContext().getResources()
.getDisplayMetrics().density);
setHeaderHeight(0);
}
private void setHeaderHeight(final int height) {
if (height <= 1) {
mHeaderView.setVisibility(View.GONE);
} else {
mHeaderView.setVisibility(View.VISIBLE);
}
// Extends refresh bar
LayoutParams lp = (LayoutParams) mHeaderContainer.getLayoutParams();
if (lp == null) {
lp = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
}
lp.height = height;
mHeaderContainer.setLayoutParams(lp);
// Refresh bar shows up from bottom to top
LinearLayout.LayoutParams headerLp = (LinearLayout.LayoutParams) mHeaderView
.getLayoutParams();
if (headerLp == null) {
headerLp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
}
headerLp.topMargin = -mHeaderHeight + height;
mHeaderView.setLayoutParams(headerLp);
if (!mIsRefreshing) {
// If scroll reaches the trigger line, start refreshing
if (height > mHeaderHeight && !mArrowUp) {
mArrow.startAnimation(AnimationUtils.loadAnimation(
getContext(), R.anim.rotate));
mText.setText("Release to update");
rotateArrow();
mArrowUp = true;
} else if (height < mHeaderHeight && mArrowUp) {
mArrow.startAnimation(AnimationUtils.loadAnimation(
getContext(), R.anim.rotate));
mText.setText("Pull down to update");
rotateArrow();
mArrowUp = false;
}else {
if (isScrool == true) {
} else {
isScrool = true;
addHeaderView(vHeader);
// Animation anim = AnimationUtils.loadAnimation(
// getContext(), R.anim.bounce_animation);
// startAnimation(anim);
smoothScrollToPosition(getChildAt(0).getTop());
// bottom_layout.setVisibility(View.VISIBLE);
}
}
}
}
private void rotateArrow() {
Drawable drawable = mArrow.getDrawable();
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.save();
canvas.rotate(180.0f, canvas.getWidth() / 2.0f,
canvas.getHeight() / 2.0f);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
drawable.draw(canvas);
canvas.restore();
mArrow.setImageBitmap(bitmap);
}
private void startRefreshing() {
mArrow.setVisibility(View.INVISIBLE);
mProgress.setVisibility(View.VISIBLE);
mText.setText("Loading...");
mIsRefreshing = true;
if (mListener != null) {
mListener.onRefresh(this);
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(final Message msg) {
super.handleMessage(msg);
int limit = 0;
switch (msg.what) {
case REFRESH:
limit = mHeaderHeight;
break;
case NORMAL:
limit = 0;
break;
}
// Elastic scrolling
if (msg.arg1 >= limit) {
setHeaderHeight(msg.arg1);
int displacement = (msg.arg1 - limit) / 10;
if (displacement == 0) {
mHandler.sendMessage(mHandler.obtainMessage(msg.what,
msg.arg1 - 1, 0));
} else {
mHandler.sendMessage(mHandler.obtainMessage(msg.what,
msg.arg1 - displacement, 0));
}
}
}
};
public interface OnRefreshListener {
public void onRefresh(RefreshableListView listView);
}
public static interface ListViewObserver {
public void onScroll(float deltaY);
}
}
here in method dispatchTouchEvent(final MotionEvent ev) i have make one condition
if (isScrool == true) {
} else {
isScrool = true;
addHeaderView(vHeader);
// Animation anim =
// AnimationUtils.loadAnimation(
// getContext(), R.anim.bounce_animation);
// startAnimation(anim);
smoothScrollToPosition(getChildAt(0).getTop());
// bottom_layout.setVisibility(View.VISIBLE);
}
here addHeaderView(vHeader);
adds header but my listview scroll down to last item can anyone could tell me what's happening here?
Try to call listView.setSelectionAfterHeaderView();. This will scroll ListView to top.
I've been stuck on this for a whole day, please help me. So I have 2 arrays filled with five dice rolls from two players and I want to set them to the according dice image that I put in my drawable. This is the original code that I have, displaying the arrays in TextView.
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice;
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
I can't figure out how to get it to display the ImageView instead.
private final static int[] diceImages = new int[] { R.drawable.d1,
R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
What I am missing?
Here's my full code, sorry its a mess. I just started to learn programming on my own and this is my first program. Any advice on making it better is appreciated too.
package com.kelvinblade.liardice;
import java.util.Random;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
int player1[] = new int[5];
int player2[] = new int[5];
TextView p1Dice, p2Dice, result, whosTurn, tvLog, score;
ImageView p1Dice1, p1Dice2, p1Dice3, p1Dice4, p1Dice5;
Button openDice, callDice;
EditText NumDice, DiceNum;
int NumOfDice, DiceNumber, turn;
int currentDiceQuantity, currentDiceFace;
boolean isOneWildCard = true;
int callLog[] = new int[70];
int playerOneEnergy, playerTwoEnergy;
boolean playerOneStart = true;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializePlaceHolders();
startGame();
}
// Initialize the Place Holders
private void initializePlaceHolders() {
p1Dice = (TextView) findViewById(R.id.tvP1Dice);
p2Dice = (TextView) findViewById(R.id.tvP2Dice);
openDice = (Button) findViewById(R.id.bOpenDice);
callDice = (Button) findViewById(R.id.bCallDice);
whosTurn = (TextView) findViewById(R.id.tvWhosTurn);
tvLog = (TextView) findViewById(R.id.tvLog);
score = (TextView) findViewById(R.id.tvScore);
result = (TextView) findViewById(R.id.tvResult);
NumDice = (EditText) findViewById(R.id.etNumDice);
DiceNum = (EditText) findViewById(R.id.etDiceNum);
p1Dice1 = (ImageView) findViewById(R.id.ivDice1);
p1Dice2 = (ImageView) findViewById(R.id.ivDice2);
p1Dice3 = (ImageView) findViewById(R.id.ivDice3);
p1Dice4 = (ImageView) findViewById(R.id.ivDice4);
p1Dice5 = (ImageView) findViewById(R.id.ivDice5);
openDice.setOnClickListener(this);
callDice.setOnClickListener(this);
}
// Game starts here
public void startGame() {
playerOneEnergy = 4;
playerTwoEnergy = 4;
playGame();
}
// Starts level
public void playGame() {
if ((playerOneEnergy != 0) && (playerTwoEnergy != 0)) {
initialize();
player1 = rollDice();
player2 = rollDice();
displayDice();
displayTurn();
} else if (playerTwoEnergy == 0) {
result.setText("Loading Next Stage!");
startGame();
} else
result.setText("Game Over!");
}
// Initialize the Variables
private void initialize() {
turn = 0;
currentDiceQuantity = 0;
currentDiceFace = 0;
result.setText("New Game.");
tvLog.setText("Game Log:");
}
// Rolls the Dice
private int[] rollDice() {
int[] diceArray = new int[5];
Random randomDice = new Random();
for (int i = 0; i < 5; i++) {
diceArray[i] = randomDice.nextInt(6) + 1;
}
return diceArray;
}
// Displays the Dice for Player 1 & 2
private void displayDice() {
StringBuffer sbfNumbers = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers.append(player1[i] + " ");
}
StringBuffer sbfNumbers2 = new StringBuffer();
for (int i = 0; i < 5; i++) {
sbfNumbers2.append(player2[i] + " ");
}
p1Dice.setText(sbfNumbers.toString());
p2Dice.setText(sbfNumbers2.toString());
// try to display the dice array as image <here's the problem>
for (int i = 0; i < 5; i++) {
p1Dice[i].setImageResource(diceImage[player1[i]]);
}
}
// Button actions
public void onClick(View v) {
switch (v.getId()) {
case R.id.bCallDice:
try {
getCall();
} catch (Exception e) {
Dialog d = new Dialog(this);
d.setTitle("Invalid call. Please try again.");
d.show();
}
if ((validInput()) && (validCall()))
runCall();
else
result.setText("Invalid call");
break;
case R.id.bOpenDice:
checkDice();
break;
}
}
private void runCall() {
currentDiceQuantity = NumOfDice;
currentDiceFace = DiceNumber;
result.setText("Valid call");
writeLog();
displayLog();
turn++;
displayTurn();
}
private void startAImove() {
Random randomAction = new Random();
int randomCall = randomAction.nextInt(1);
if ((randomCall == 0) && (!isFirstMove()))
checkDice();
else {
while (!validCall()) {
NumOfDice = randomAction.nextInt(5) + 1;
DiceNumber = randomAction.nextInt(5) + 1;
}
runCall();
}
}
// Gets the Call from Player 1
private void getCall() {
String s = NumDice.getText().toString();
NumOfDice = Integer.parseInt(s);
String s1 = DiceNum.getText().toString();
DiceNumber = Integer.parseInt(s1);
if (DiceNumber == 1) {
isOneWildCard = false;
}
}
// Checks to see if the call is a valid input
private boolean validInput() {
int MaxNumOfDice = 5;
int MaxDiceQuantity = 6;
if ((NumOfDice <= MaxNumOfDice * 2) && (DiceNumber <= MaxDiceQuantity)) {
return true;
} else
return false;
}
// Checks to see if Valid Call
private boolean validCall() {
if (NumOfDice > currentDiceQuantity) {
return true;
} else if (((NumOfDice == currentDiceQuantity) && (currentDiceFace != 1))
&& ((DiceNumber == 1) || (DiceNumber > currentDiceFace))) {
return true;
} else {
return false;
}
}
// Writes to Log
private void writeLog() {
callLog[turn * 2] = currentDiceQuantity;
callLog[turn * 2 + 1] = currentDiceFace;
}
// Display Log
private void displayLog() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Game Log:\n");
for (int i = 0; i < turn + 1; i++) {
sbfNumbers.append((i + 1) + ": Player" + (i % 2 + 1) + " "
+ callLog[i * 2] + "x" + callLog[i * 2 + 1] + "\n");
}
tvLog.setText(sbfNumbers.toString());
}
// Display who's turn
public void displayTurn() {
if (whichPlayersTurn() == 1)
whosTurn.setText("Player 1's Turn...");
else {
whosTurn.setText("Player 2's Turn...");
// startAImove();
}
}
// Checks who's turn
private int whichPlayersTurn() {
boolean isTurnEven = false;
if (turn % 2 == 0)
isTurnEven = true;
if (((playerOneStart) && (isTurnEven))
|| ((!playerOneStart) && (!isTurnEven))) {
return 1;
} else
return 2;
}
// Checks if it's the first move
private boolean isFirstMove() {
if (currentDiceQuantity == 0)
return true;
else
return false;
}
// Checks the Player 1 & 2 for the Dice
private void checkDice() {
if (!isFirstMove()) {
int DiceCount = 0;
for (int i = 0; i < 5; i++) {
if (player1[i] == DiceNumber)
DiceCount++;
if (player2[i] == DiceNumber)
DiceCount++;
if ((player1[i] == 1) && (isOneWildCard))
DiceCount++;
if ((player2[i] == 1) && (isOneWildCard))
DiceCount++;
}
if (((DiceCount >= NumOfDice) && (whichPlayersTurn() != 1))
|| ((DiceCount < NumOfDice) && (whichPlayersTurn() == 1))) {
result.setText("Player 1 Wins!");
playerTwoEnergy--;
playerOneStart = false;
} else {
result.setText("Player 1 Loses!");
playerOneEnergy--;
playerOneStart = true;
}
displayWinLost();
playGame();
} else
result.setText("Can not open on first move!");
}
// Display Win / Lose
private void displayWinLost() {
StringBuffer sbfNumbers = new StringBuffer();
sbfNumbers.append("Player One Energy : " + playerOneEnergy
+ "\nPlayer Two Energy: " + playerTwoEnergy);
score.setText(sbfNumbers.toString());
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
}
Thank you so much in advanced. Any help is highly appreciated. Thanks again!!
In your code imageViews are not in an array, so you cannot do p1Dice[i] .
So please change to
private ImageView[] p1Dice = new ImageView[5];
or
p1Dice1.setImageResource(diceImage[player1[0]]);
p1Dice2.setImageResource(diceImage[player1[1]]);
p1Dice3.setImageResource(diceImage[player1[2]]);
The ImageViews are not in an array, so you cannot do p1Dice[i].something()
Change the declaration to ImageViews to this
private ImageView[] p1Dice = new ImageView[5];