I'm developing an android game, trying to store the character's coordinates. I'm using the onSaveInstanceState and onRestoreInstanceState methods. But when I tested the coordinates get's changed.
So it loads the correct value but after that it saves a bad number then it loads this bad value.
Class1
package hu.cig.vob;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import cug.hu.vob.R;
public class Level extends Activity {
private LevelView lv;
private LinearLayout linearL;
private Button left, right, jump, fire;
private mListener l = new mListener();
//Konstansok az activity allapotanak mentesehez
private String playerX = "PlayerX",playerY="PlayerY",playerH="PlayerH";
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level_layout);
final ImageView healthBar = (ImageView) findViewById(R.id.life_view);
Drawable d = getResources().getDrawable(R.drawable.main_screen_bg);
linearL = (LinearLayout) findViewById(R.id.linear_layout);
linearL.setBackgroundDrawable(d);
lv = new LevelView(getApplicationContext(), getIntent().getIntExtra(
MainActivity.LEVEL_EXTRA, 0), getWindowManager());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.FILL_PARENT);
lv.setLayoutParams(params);
linearL.addView(lv, 0);
left = (Button) findViewById(R.id.left);
right = (Button) findViewById(R.id.right);
jump = (Button) findViewById(R.id.jump);
fire = (Button) findViewById(R.id.fire);
left.setOnTouchListener(l);
right.setOnTouchListener(l);
jump.setOnTouchListener(l);
fire.setOnTouchListener(l);
lv.setOnClickListener(new OnClickListener() {
// Game over screen esetén kilép
#Override
public void onClick(View v) {
if (lv.getGameState()) {
finish();
}
}
});
// Életcsik frissitése az életnek megfelelően
new Thread() {
#Override
public void run() {
while (true) {
if (lv.getRobot().getHealth() <= 0) {
runOnUiThread(new Runnable() {
#Override
public void run() {
healthBar.setImageResource(R.drawable.battery5);
}
});
} else if (lv.getRobot().getHealth() <= 25) {
runOnUiThread(new Runnable() {
#Override
public void run() {
healthBar.setImageResource(R.drawable.battery4);
}
});
} else if (lv.getRobot().getHealth() <= 50) {
runOnUiThread(new Runnable() {
#Override
public void run() {
healthBar.setImageResource(R.drawable.battery3);
}
});
} else if (lv.getRobot().getHealth() <= 75) {
runOnUiThread(new Runnable() {
#Override
public void run() {
healthBar.setImageResource(R.drawable.battery2);
}
});
}else if(lv.getRobot().getHealth() >= 75){
runOnUiThread(new Runnable() {
#Override
public void run() {
healthBar.setImageResource(R.drawable.battery);
}
});
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
#Override
protected void onPause() {
overridePendingTransition(0, 0);
super.onPause();
}
// TODO:
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
lv.getRobot().setX(savedInstanceState.getInt(playerX));
lv.getRobot().setY(savedInstanceState.getInt(playerY));
Log.d("LoL","Loaded y:"+savedInstanceState.getInt(playerY));
lv.getRobot().setHealth(savedInstanceState.getInt(playerH));
super.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(playerX , lv.getRobot().getX());
outState.putInt(playerY, lv.getRobot().getY());
Log.d("LoL","Saved y:"+lv.getRobot().getY());
outState.putInt(playerH, lv.getRobot().getHealth() );
super.onSaveInstanceState(outState);
}
// iránygombok kezelése
private class mListener implements OnTouchListener {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
switch (v.getId()) {
case R.id.left:
lv.getRobot().moveLeft();
break;
case R.id.right:
lv.getRobot().moveRight();
break;
case R.id.jump:
lv.getRobot().jump();
break;
case R.id.fire:
lv.getRobot().shot();
break;
}
break;
case MotionEvent.ACTION_UP:
switch (v.getId()) {
case R.id.left:
lv.getRobot().stopMovingLeft();
break;
case R.id.right:
lv.getRobot().stopMovingRight();
break;
case R.id.fire:
lv.getRobot()._shot();
break;
}
break;
}
return true;
}
}
}
class2
package hu.cig.vob;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import cug.hu.vob.R;
public class Robot {
private Bitmap icon, currIcon, iconShot;
private int x, y, speedX = 0, speedY = 0, health = 100;
private final int MOVESPEED = 3, JumpSpeed = 15;
private boolean isMovingLeft = false, isMovingRight = false,
isFalling = true, isJumping = false, canJump = true;
private Rect bottom, horizontal;
private Context context;
private List<Bullet> bullets = Collections
.synchronizedList(new ArrayList<Bullet>());
public Robot(int in_x, int in_y, Bitmap i, float sc, Context c) {
context = c;
icon = i;
currIcon = icon;
iconShot = BitmapFactory.decodeResource(c.getResources(),
R.drawable.shot_right);
x = in_x * (icon.getWidth()/2);
y = in_y * (icon.getHeight()/2);
y = (int) (sc - y);
// for colliding
horizontal = new Rect((int) (x + icon.getWidth() * (31.5 / 100)),
y + 5, (int) (x + icon.getWidth() - icon.getWidth()
* (31.5 / 100)), y + icon.getHeight() - 5);
bottom = new Rect((int) (x + icon.getWidth() * (31.5 / 100) + 5), y
+ icon.getHeight() - 10, (int) (x + icon.getWidth()
- icon.getWidth() * (31.5 / 100) - 5), y + icon.getHeight());
}
public void update(List<Block> blocks) {
int oldX = x, oldY = y;
if (!(x + speedX < 0 || x + speedX > LevelView.intScreenWidth)) {
x += speedX;
}
updateRect();
for (int i = 0; i < blocks.size(); i++) {
if (horizontal.intersect(blocks.get(i).getRect())) {
stopMovingRight();
stopMovingLeft();
x = oldX;
updateRect();
}
}
if (bullets.size() > 0) {
Iterator<Bullet> it = bullets.iterator();
while (it.hasNext()) {
Bullet b = it.next();
if (b.getCx() > LevelView.screenWidth) {
it.remove();
} else {
b.update();
}
Iterator<Block> itt = blocks.iterator();
while (itt.hasNext()) {
Block bb = itt.next();
if (bb.getRect().intersect(b.getRect())) {
it.remove();
}
}
}
}
// #graviti"
if (isJumping) {
y -= speedY;
speedY--;
if (speedY == 0) {
isFalling = true;
isJumping = false;
}
updateRect();
}
if (isFalling) {
y += JumpSpeed - 5;
canJump = false;
updateRect();
}
for (Block b : blocks) {
if (bottom.intersect(b.getRect())) {
y = oldY;
updateRect();
canJump = true;
}
}
}
private void updateRect() {
horizontal = new Rect((int) (x + icon.getWidth() * (31.5 / 100)),
y + 10, (int) (x + icon.getWidth() - icon.getWidth()
* (31.5 / 100)), y + icon.getHeight() - 10);
bottom = new Rect((int) (x + icon.getWidth() * (31.5 / 100) + 5), y
+ icon.getHeight() - 10, (int) (x + icon.getWidth()
- icon.getWidth() * (31.5 / 100) - 5), y + icon.getHeight() - 2);
}
public void moveLeft() {
speedX = -MOVESPEED;
isMovingLeft = true;
}
public void moveRight() {
speedX = MOVESPEED;
isMovingRight = true;
}
public void stopMovingLeft() {
isMovingLeft = false;
stop();
}
public void stopMovingRight() {
isMovingRight = false;
stop();
}
public void stop() {
if (isMovingRight == false && isMovingLeft == false) {
speedX = 0;
}
if (isMovingRight == true && isMovingLeft == false) {
moveRight();
}
if (isMovingRight == false && isMovingLeft == true) {
moveLeft();
}
}
public Bitmap getIcon() {
return currIcon;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getSpeed() {
return speedX;
}
public boolean isMovingLeft() {
return isMovingLeft;
}
public boolean isMovingRight() {
return isMovingRight;
}
public Rect getBottomRect() {
return bottom;
}
public Rect getHRect() {
return horizontal;
}
public int getHealth() {
return health;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setHealth(int health) {
this.health = health;
}
public void shot() {
currIcon = iconShot;
Bullet b = new Bullet((float) (x + iconShot.getWidth()),
(float) (y + ((26.31 * iconShot.getHeight()) / 100)),
Helper.convertPx_Dpi(10, context), 2);
bullets.add(b);
}
public void _shot() {
currIcon = icon;
}
public List<Bullet> getBullets() {
return bullets;
}
public void jump() {
if (!isJumping && canJump) {
isJumping = true;
isFalling = false;
speedY = JumpSpeed;
}
}
public void increaseHealth(int x){
health += x;
if(health > 100){
health = 100;
}
}
public void degreeseHealth(int a) {
health -= a;
}
}
Your app can resume while obscured by the lock screen. If you want to tell the difference between "resume is hidden by a lock screen" and "resume is actually displayed" you can check your window focus.
See Making Android Games that Play Nice for more details.
A different way to get a similar "wait until actually displayed" is to wait for the first Activity.onUserInteraction after a resume before restarting your game.
Related
this is my code i m successfully zooming from center but i want to zoom in from the touch coordinates like instagram image zoom.I tried this code till now.Help me through it please.
ZoomImageActivity.java
public class ZoomImageActivity extends AppCompatActivity {
ImageView ivBG;
private ZoomImageHelper imageZoomHelper;
private View zoomableView = null;
View.OnTouchListener zoomTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent ev) {
switch (ev.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
if (ev.getPointerCount() == 2 && zoomableView == null)
zoomableView = view;
break;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zoom_image);
ivBG = (ImageView) findViewById(R.id.ivBG);
ivBG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
ivBG.setOnTouchListener(zoomTouchListener);
imageZoomHelper = new ZoomImageHelper(this, tvParam);
imageZoomHelper.addOnZoomListener(new ZoomImageHelper.OnZoomListener() {
#Override
public void onImageZoomStarted(View view) {
}
#Override
public void onImageZoomEnded(View view) {
zoomableView = null;
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return imageZoomHelper.onDispatchTouchEvent(ev, zoomableView) || super.dispatchTouchEvent(ev);
}}
ZoomImageHelper.java
public class ZoomImageHelper {
private View zoomableView = null;
private ViewGroup parentOfZoomableView;
private ViewGroup.LayoutParams zoomableViewLP;
private FrameLayout.LayoutParams zoomableViewFrameLP;
private Dialog dialog;
private View placeholderView;
private int viewIndex;
private View darkView;
private double originalDistance;
private int[] twoPointCenter;
private int[] originalXY;
private WeakReference<Activity> activityWeakReference;
private boolean isAnimatingDismiss = false;
private List<OnZoomListener> zoomListeners = new ArrayList<>();
public ZoomImageHelper(Activity activity) {
this.activityWeakReference = new WeakReference<>(activity);
}
public boolean onDispatchTouchEvent(MotionEvent ev, View view) {
Activity activity;
if ((activity = activityWeakReference.get()) == null)
return false;
if (ev.getPointerCount() == 2) {
if (zoomableView == null) {
if (view != null) {
zoomableView = view;
// get view's original location relative to the window
originalXY = new int[2];
view.getLocationInWindow(originalXY);
// this FrameLayout will be the zoomableView's temporary parent
FrameLayout frameLayout = new FrameLayout(view.getContext());
// this view is to gradually darken the backdrop as user zooms
darkView = new View(view.getContext());
darkView.setBackgroundColor(Color.BLACK);
darkView.setAlpha(0f);
// adding darkening backdrop to the frameLayout
frameLayout.addView(darkView, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT));
// the Dialog that will hold the FrameLayout
dialog = new Dialog(activity,
android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
dialog.addContentView(frameLayout,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
dialog.show();
// get the parent of the zoomable view and get it's index and layout param
parentOfZoomableView = (ViewGroup) zoomableView.getParent();
viewIndex = parentOfZoomableView.indexOfChild(zoomableView);
this.zoomableViewLP = zoomableView.getLayoutParams();
// this is the new layout param for the zoomableView
zoomableViewFrameLP = new FrameLayout.LayoutParams(
view.getWidth(), view.getHeight());
zoomableViewFrameLP.leftMargin = originalXY[0];
zoomableViewFrameLP.topMargin = originalXY[1];
// this view will hold the zoomableView's position temporarily
placeholderView = new View(activity);
// setting placeholderView's background to zoomableView's drawingCache
// this avoids flickering when adding/removing views
zoomableView.setDrawingCacheEnabled(true);
BitmapDrawable placeholderDrawable = new BitmapDrawable(
activity.getResources(),
Bitmap.createBitmap(zoomableView.getDrawingCache()));
if (Build.VERSION.SDK_INT >= 16) {
placeholderView.setBackground(placeholderDrawable);
} else {
placeholderView.setBackgroundDrawable(placeholderDrawable);
}
// placeholderView takes the place of zoomableView temporarily
parentOfZoomableView.addView(placeholderView, zoomableViewLP);
// zoomableView has to be removed from parent view before being added to it's
// new parent
parentOfZoomableView.removeView(zoomableView);
frameLayout.addView(zoomableView, zoomableViewFrameLP);
// using a post to remove placeholder's drawing cache
zoomableView.post(new Runnable() {
#Override
public void run() {
if (dialog != null) {
if (Build.VERSION.SDK_INT >= 16) {
placeholderView.setBackground(null);
} else {
placeholderView.setBackgroundDrawable(null);
}
zoomableView.setDrawingCacheEnabled(false);
}
}
});
// Pointer variables to store the original touch positions
MotionEvent.PointerCoords pointerCoords1 = new MotionEvent.PointerCoords();
ev.getPointerCoords(0, pointerCoords1);
MotionEvent.PointerCoords pointerCoords2 = new MotionEvent.PointerCoords();
ev.getPointerCoords(1, pointerCoords2);
// storing distance between the two positions to be compared later on for
// zooming
originalDistance = (int) getDistance(pointerCoords1.x, pointerCoords2.x,
pointerCoords1.y, pointerCoords2.y);
// storing center point of the two pointers to move the view according to the
// touch position
twoPointCenter = new int[]{
(int) ((pointerCoords2.x + pointerCoords1.x) / 2),
(int) ((pointerCoords2.y + pointerCoords1.y) / 2)
};
sendZoomEventToListeners(zoomableView, true);
return true;
}
} else {
MotionEvent.PointerCoords pointerCoords1 = new MotionEvent.PointerCoords();
ev.getPointerCoords(0, pointerCoords1);
MotionEvent.PointerCoords pointerCoords2 = new MotionEvent.PointerCoords();
ev.getPointerCoords(1, pointerCoords2);
int[] newCenter = new int[]{
(int) ((pointerCoords2.x + pointerCoords1.x) / 2),
(int) ((pointerCoords2.y + pointerCoords1.y) / 2)
};
int currentDistance = (int) getDistance(pointerCoords1.x, pointerCoords2.x,
pointerCoords1.y, pointerCoords2.y);
double pctIncrease = (currentDistance - originalDistance) / originalDistance;
zoomableView.setScaleX((float) (1 + pctIncrease));
zoomableView.setScaleY((float) (1 + pctIncrease));
updateZoomableViewMargins(newCenter[0] - twoPointCenter[0] + originalXY[0],
newCenter[1] - twoPointCenter[1] + originalXY[1]);
darkView.setAlpha((float) (pctIncrease / 8));
return true;
}
} else {
if (zoomableView != null && !isAnimatingDismiss) {
isAnimatingDismiss = true;
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 1f);
valueAnimator.setDuration(activity.getResources()
.getInteger(android.R.integer.config_shortAnimTime));
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
float scaleYStart = zoomableView.getScaleY();
float scaleXStart = zoomableView.getScaleX();
int leftMarginStart = zoomableViewFrameLP.leftMargin;
int topMarginStart = zoomableViewFrameLP.topMargin;
float alphaStart = darkView.getAlpha();
float scaleYEnd = 1f;
float scaleXEnd = 1f;
int leftMarginEnd = originalXY[0];
int topMarginEnd = originalXY[1];
float alphaEnd = 0f;
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float animatedFraction = valueAnimator.getAnimatedFraction();
if (animatedFraction < 1) {
zoomableView.setScaleX(((scaleXEnd - scaleXStart) * animatedFraction) +
scaleXStart);
zoomableView.setScaleY(((scaleYEnd - scaleYStart) * animatedFraction) +
scaleYStart);
updateZoomableViewMargins(
((leftMarginEnd - leftMarginStart) * animatedFraction) +
leftMarginStart,
((topMarginEnd - topMarginStart) * animatedFraction) +
topMarginStart);
darkView.setAlpha(((alphaEnd - alphaStart) * animatedFraction) +
alphaStart);
} else {
dismissDialogAndViews();
}
}
});
valueAnimator.start();
return true;
}
}
return false;
}
void updateZoomableViewMargins(float left, float top) {
if (zoomableView != null && zoomableViewFrameLP != null) {
zoomableViewFrameLP.leftMargin = (int) left;
zoomableViewFrameLP.topMargin = (int) top;
zoomableView.setLayoutParams(zoomableViewFrameLP);
}
}
/**
* Dismiss dialog and set views to null for garbage collection
*/
private void dismissDialogAndViews() {
sendZoomEventToListeners(zoomableView, false);
if (zoomableView != null) {
zoomableView.setVisibility(View.VISIBLE);
zoomableView.setDrawingCacheEnabled(true);
BitmapDrawable placeholderDrawable = new BitmapDrawable(
zoomableView.getResources(),
Bitmap.createBitmap(zoomableView.getDrawingCache()));
if (Build.VERSION.SDK_INT >= 16) {
placeholderView.setBackground(placeholderDrawable);
} else {
placeholderView.setBackgroundDrawable(placeholderDrawable);
}
ViewGroup parent = (ViewGroup) zoomableView.getParent();
parent.removeView(zoomableView);
this.parentOfZoomableView.addView(zoomableView, viewIndex, zoomableViewLP);
this.parentOfZoomableView.removeView(placeholderView);
zoomableView.setDrawingCacheEnabled(false);
zoomableView.post(new Runnable() {
#Override
public void run() {
dismissDialog();
}
});
zoomableView = null;
} else {
dismissDialog();
}
isAnimatingDismiss = false;
}
public void addOnZoomListener(OnZoomListener onZoomListener) {
zoomListeners.add(onZoomListener);
}
public void removeOnZoomListener(OnZoomListener onZoomListener) {
zoomListeners.remove(onZoomListener);
}
private void sendZoomEventToListeners(View zoomableView, boolean zoom) {
for (OnZoomListener onZoomListener : zoomListeners) {
if (zoom)
onZoomListener.onImageZoomStarted(zoomableView);
else
onZoomListener.onImageZoomEnded(zoomableView);
}
}
private void dismissDialog() {
if (dialog != null) {
dialog.dismiss();
dialog = null;
}
darkView = null;
resetOriginalViewAfterZoom();
}
private void resetOriginalViewAfterZoom() {
zoomableView.invalidate();
zoomableView = null;
}
/**
* Get distance between two points
*
* #param x1
* #param x2
* #param y1
* #param y2
* #return distance
*/
private double getDistance(double x1, double x2, double y1, double y2) {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
}
public interface OnZoomListener {
void onImageZoomStarted(View view);
void onImageZoomEnded(View view);
}}
I need the image to zoom and pan from its touch coordinates not from center.. Thanks in advance.
I want one of my ViewGroup to be movable. Let's say, I want to click on it and the content below it reveals. On second click it closes again. Kind of sliding menu behaviour.
Here are my classes:
Custom scroller:
public class MyScroller implements Runnable {
private static final String TAG = "MY_SCROLLER";
private static final int ANIMATION_DURATION = 500;
private final Scroller mScroller;
private View mScrollingView;
private int lastX = 0;
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
MyScroller(final View view) {
mScroller = new android.widget.Scroller(view.getContext(), sInterpolator);
mScrollingView = view;
}
public void start(int initialVelocity) {
Log.d(TAG, "start() called");
int initialX = mScrollingView.getScrollX();
int maxX = mScrollingView.getWidth();
mScroller.startScroll(0, 0, maxX, 0, ANIMATION_DURATION);
lastX = initialX;
mScrollingView.post(this);
}
public void run() {
Log.d(TAG, "run() called");
if (mScroller.isFinished()) {
mScrollingView.invalidate();
return;
}
boolean more = mScroller.computeScrollOffset();
int x = mScroller.getCurrX();
int diff = x - lastX;
if (diff != 0) {
Log.d(TAG, "x = " + x);
mScrollingView.offsetLeftAndRight(diff);
mScrollingView.invalidate();
lastX = x;
} else {
forceFinished();
}
if (more) {
mScrollingView.postDelayed(this, 16);
}
}
void forceFinished() {
if (!mScroller.isFinished()) {
mScroller.forceFinished(true);
mScrollingView.invalidate();
}
}
}
and usage:
viewGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyScroller(v).start(0);
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyScroller(v).start(0);
}
});
For Button everything works fine - it smoothly moves.
But ViewGroups that I tried leave a trail like on screenshot.
RelativeLayout with Button inside left a trail.
Standalone Button moved perfectly.
What am I missing here?
I am trying to create an infinite pager from a HorizontalScrollView.
It does infinitely scroll by continuously rearranging the children views as needed, but once it has to start moving the views (adding to the left or the right) it is no longer scrolling smoothly. I am trying to figure out how to get it to scroll to the next page smoothly even after it changes the child position.
Here is the class as I have it so far:
import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
public class PagerInfinite extends HorizontalScrollView {
private LinearLayout contents;
private Map<Integer, Integer> childWidths = new HashMap<Integer, Integer>();
private int childSpacing = 0;
private int activePageIndex = 1;
private float oldX = 0f;
private float oldY = 0f;
private boolean firstScroll = true;
public PagerInfinite(Context context, AttributeSet attrs) {
super(context, attrs);
this.contents = new LinearLayout(context);
this.contents.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
this.addView(this.contents);
setVerticalScrollBarEnabled(false);
setHorizontalScrollBarEnabled(false);
}
#Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
for (int i = 0; i < this.contents.getChildCount(); i++) {
View child = this.contents.getChildAt(i);
int width = child.getWidth();
if(width != 0) {
this.childWidths.put(i, width);
}
}
if(this.childWidths.size() > 0 && this.firstScroll) {
this.smoothScrollTo(this.getActivePageOffset(), 0);
this.firstScroll = false;
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
#Override
protected float getLeftFadingEdgeStrength() {
return 0.0f;
}
#Override
protected float getRightFadingEdgeStrength() {
return 0.0f;
}
public void addPage(View child) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, this.childSpacing, 0);
child.setLayoutParams(params);
if(this.contents.getChildCount() <= 1) {
this.contents.addView(child);
} else if(this.contents.getChildCount() <= 2) {
this.contents.addView(child, 0);
} else {
View last = this.contents.getChildAt(0);
this.contents.removeView(last);
this.contents.addView(last);
this.contents.addView(child, 0);
}
this.contents.requestLayout();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
boolean result = super.onTouchEvent(event);
switch(event.getAction()) {
case(MotionEvent.ACTION_DOWN):
this.oldX = event.getX();
this.oldY = event.getY();
break;
case(MotionEvent.ACTION_UP):
float newX = event.getX();
float newY = event.getY();
float deltaX = newX - this.oldX;
float deltaY = newY - this.oldY;
// Use deltaX and deltaY to determine the direction
if(Math.abs(deltaX) > Math.abs(deltaY)) {
if(deltaX > 0) {
// right
if(this.activePageIndex <= 1) {
this.buildLeft();
} else {
this.activePageIndex -= 1;
}
} else {
// left
if(this.activePageIndex >= this.contents.getChildCount() - 2) {
this.buildRight();
} else {
this.activePageIndex += 1;
}
}
}
this.smoothScrollTo(this.getActivePageOffset(), 0);
break;
}
return result;
}
private void buildLeft() {
View view = this.contents.getChildAt(this.contents.getChildCount() - 1);
this.contents.removeView(view);
this.contents.addView(view, 0);
}
private void buildRight() {
View view = this.contents.getChildAt(0);
this.contents.removeView(view);
this.contents.addView(view);
}
private int getActivePageOffset() {
Log.d(LCHApplication.TAG, "ActiveIndex = " + this.activePageIndex);
if(this.activePageIndex == 0) {
return 0;
}
if(this.activePageIndex == this.contents.getChildCount() - 1) {
return this.contents.getWidth();
}
int offset = 0;
for(Map.Entry<Integer, Integer> entry : this.childWidths.entrySet()) {
if(entry.getKey() < this.activePageIndex) {
offset += entry.getValue() + this.childSpacing;
} else {
break;
}
}
offset += (this.childWidths.get(this.activePageIndex) / 2);
offset -= (LCHApplication.instance.width / 2);
return offset;
}
public boolean hasPage(View v) {
return this.contents.indexOfChild(v) != -1;
}
public void removePage(View v) {
int index = this.contents.indexOfChild(v);
this.contents.removeView(v);
this.childWidths.remove(index);
}
public int getCurrentPageIndex() {
return this.activePageIndex;
}
public int getPageCount() {
return this.contents.getChildCount();
}
public void removeAllPages() {
this.contents.removeAllViews();
this.childWidths = new HashMap<Integer, Integer>();
}
public void cycle() {
if(this.activePageIndex < this.contents.getChildCount() - 1) {
this.activePageIndex += 1;
} else {
this.activePageIndex = 0;
}
this.smoothScrollTo(this.getActivePageOffset(), 0);
}
public int getChildSpacing() {
return this.childSpacing;
}
public void setChildSpacing(int spacing) {
this.childSpacing = spacing;
}
}
Its too late but I believe my answer may helpful to somebody else who has same issue.
Sample project with infinite pages - with page swipe effect
https://github.com/UdaySravanK/USK_APIs
In details, I am looking for an example exactly like below image. I got a good example in this link https://github.com/woozzu/IndexableListView. Its works fine as my requirement.But problem when i implementing to my project it is showing error in list view. below is my code plz help me. i am new to this topic. Thank you in advance!
looking for:
here is my code below plz say my mistake..
MainActivity .java
public class MainActivity extends Activity implements SearchView.OnQueryTextListener,SearchView.OnCloseListener {
private ListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
EfficientAdapter2 objectAdapter1;
int textlength=0;
private CheckBox checkStat, checkRoutine, checkTat;
private GestureDetector mGestureDetector;
private ArrayList<CountriesList> elements;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan"," txtScanResult ");
//Arrays.sort(CountriesList.name);
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this, QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed", Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE", Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency", Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
objectAdapter = new EfficientAdapter(this, elements );
listView.setAdapter(objectAdapter);
Button refreshButton= (Button)findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
objectAdapter1 = new EfficientAdapter2(MainActivity.this);
// objectAdapter = new EfficientAdapter(MainActivity.this);// adapter with new data
listView.setAdapter(objectAdapter1);
Log.i("notifyDataSetChanged", "data updated");
objectAdapter1.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.java
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private AlphabetIndexer alphaIndexer;
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context, ArrayList<CountriesList> elements) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
public int getCount() {
return CountriesList.name.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.name);
holder.text2 = (TextView) convertView
.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView
.findViewById(R.id.date);
holder.text4 = (TextView) convertView
.findViewById(R.id.age);
holder.text5 = (TextView) convertView
.findViewById(R.id.gender);
holder.text6 = (TextView) convertView
.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView
.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView
.findViewById(R.id.bedno);
holder.btnList = (Button)convertView.findViewById(R.id.listbutton);
// holder.btnList.setOnClickListener(this);
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(CountriesList.name[position]);
holder.text2.setText(CountriesList.mrn[position]);
holder.text3.setText(CountriesList.actualstart[position]);
holder.text4.setText(CountriesList.age[position]);
holder.text5.setText(CountriesList.gender[position]);
holder.text6.setText(CountriesList.wardNo[position]);
holder.text7.setText(CountriesList.roomNo[position]);
holder.text8.setText(CountriesList.bedNo[position]);
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public int getPositionForSection(int section) {
// If there is no item for current section, previous section will be selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(k)))
return j;
}
} else {
// if (StringMatcher.match(String.valueOf(getItem(j).charAt(0)), String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
IndexableListView.java
public class IndexableListView extends ListView {
private boolean mIsFastScrollEnabled = false;
private IndexScroller mScroller = null;
private GestureDetector mGestureDetector = null;
public IndexableListView(Context context) {
super(context);
}
public IndexableListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IndexableListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
#Override
public boolean isFastScrollEnabled() {
return mIsFastScrollEnabled;
}
#Override
public void setFastScrollEnabled(boolean enabled) {
mIsFastScrollEnabled = enabled;
if (mIsFastScrollEnabled) {
if (mScroller == null)
mScroller = new IndexScroller(getContext(), this);
} else {
if (mScroller != null) {
mScroller.hide();
mScroller = null;
}
}
}
#Override
public void draw(Canvas canvas) {
super.draw(canvas);
// Overlay index bar
if (mScroller != null)
mScroller.draw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
// Intercept ListView's touch event
if (mScroller != null && mScroller.onTouchEvent(ev))
return true;
if (mGestureDetector == null) {
mGestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
// If fling happens, index bar shows
mScroller.show();
return super.onFling(e1, e2, velocityX, velocityY);
}
});
}
mGestureDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
#Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
if (mScroller != null)
mScroller.setAdapter(adapter);
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mScroller != null)
mScroller.onSizeChanged(w, h, oldw, oldh);
}
}
StringMatcher.java
public class StringMatcher {
public static boolean match(String value, String keyword) {
if (value == null || keyword == null)
return false;
if (keyword.length() > value.length())
return false;
int i = 0, j = 0;
do {
if (isKorean(value.charAt(i)) && isInitialSound(keyword.charAt(j))) {
} else {
if (keyword.charAt(j) == value.charAt(i)) {
i++;
j++;
} else if (j > 0)
break;
else
i++;
}
} while (i < value.length() && j < keyword.length());
return (j == keyword.length())? true : false;
}
private static boolean isKorean(char c) {
return false;
}
private static boolean isInitialSound(char c) {
return false;
}
}
IndexScroller.java
public class IndexScroller {
private static final int STATE_HIDDEN = 0;
private static final int STATE_SHOWING = 1;
private static final int STATE_SHOWN = 2;
private static final int STATE_HIDING = 3;
public IndexScroller(Context context, ListView lv) {
mDensity = context.getResources().getDisplayMetrics().density;
mScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
mListView = lv;
setAdapter(mListView.getAdapter());
mIndexbarWidth = 20 * mDensity;
mIndexbarMargin = 10 * mDensity;
mPreviewPadding = 5 * mDensity;
}
public void draw(Canvas canvas) {
if (mState == STATE_HIDDEN)
return;
// mAlphaRate determines the rate of opacity
Paint indexbarPaint = new Paint();
indexbarPaint.setColor(Color.BLACK);
indexbarPaint.setAlpha((int) (64 * mAlphaRate));
indexbarPaint.setAntiAlias(true);
canvas.drawRoundRect(mIndexbarRect, 5 * mDensity, 5 * mDensity, indexbarPaint);
if (mSections != null && mSections.length > 0) {
// Preview is shown when mCurrentSection is set
if (mCurrentSection >= 0) {
Paint previewPaint = new Paint();
previewPaint.setColor(Color.BLACK);
previewPaint.setAlpha(96);
previewPaint.setAntiAlias(true);
previewPaint.setShadowLayer(3, 0, 0, Color.argb(64, 0, 0, 0));
Paint previewTextPaint = new Paint();
previewTextPaint.setColor(Color.WHITE);
previewTextPaint.setAntiAlias(true);
previewTextPaint.setTextSize(50 * mScaledDensity);
float previewTextWidth = previewTextPaint.measureText(mSections[mCurrentSection]);
float previewSize = 2 * mPreviewPadding + previewTextPaint.descent() - previewTextPaint.ascent();
RectF previewRect = new RectF((mListViewWidth - previewSize) / 2
, (mListViewHeight - previewSize) / 2
, (mListViewWidth - previewSize) / 2 + previewSize
, (mListViewHeight - previewSize) / 2 + previewSize);
canvas.drawRoundRect(previewRect, 5 * mDensity, 5 * mDensity, previewPaint);
canvas.drawText(mSections[mCurrentSection], previewRect.left + (previewSize - previewTextWidth) / 2 - 1
, previewRect.top + mPreviewPadding - previewTextPaint.ascent() + 1, previewTextPaint);
}
Paint indexPaint = new Paint();
indexPaint.setColor(Color.WHITE);
indexPaint.setAlpha((int) (255 * mAlphaRate));
indexPaint.setAntiAlias(true);
indexPaint.setTextSize(12 * mScaledDensity);
float sectionHeight = (mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length;
float paddingTop = (sectionHeight - (indexPaint.descent() - indexPaint.ascent())) / 2;
for (int i = 0; i < mSections.length; i++) {
float paddingLeft = (mIndexbarWidth - indexPaint.measureText(mSections[i])) / 2;
canvas.drawText(mSections[i], mIndexbarRect.left + paddingLeft
, mIndexbarRect.top + mIndexbarMargin + sectionHeight * i + paddingTop - indexPaint.ascent(), indexPaint);
}
}
}
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// If down event occurs inside index bar region, start indexing
if (mState != STATE_HIDDEN && contains(ev.getX(), ev.getY())) {
setState(STATE_SHOWN);
// It demonstrates that the motion event started from index bar
mIsIndexing = true;
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
return true;
}
break;
case MotionEvent.ACTION_MOVE:
if (mIsIndexing) {
// If this event moves inside index bar
if (contains(ev.getX(), ev.getY())) {
// Determine which section the point is in, and move the list to that section
mCurrentSection = getSectionByPoint(ev.getY());
mListView.setSelection(mIndexer.getPositionForSection(mCurrentSection));
}
return true;
}
break;
case MotionEvent.ACTION_UP:
if (mIsIndexing) {
mIsIndexing = false;
mCurrentSection = -1;
}
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
break;
}
return false;
}
public void onSizeChanged(int w, int h, int oldw, int oldh) {
mListViewWidth = w;
mListViewHeight = h;
mIndexbarRect = new RectF(w - mIndexbarMargin - mIndexbarWidth
, mIndexbarMargin
, w - mIndexbarMargin
, h - mIndexbarMargin);
}
public void show() {
if (mState == STATE_HIDDEN)
setState(STATE_SHOWING);
else if (mState == STATE_HIDING)
setState(STATE_HIDING);
}
public void hide() {
if (mState == STATE_SHOWN)
setState(STATE_HIDING);
}
public void setAdapter(Adapter adapter) {
if (adapter instanceof SectionIndexer) {
mIndexer = (SectionIndexer) adapter;
mSections = (String[]) mIndexer.getSections();
}
}
private void setState(int state) {
if (state < STATE_HIDDEN || state > STATE_HIDING)
return;
mState = state;
switch (mState) {
case STATE_HIDDEN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_SHOWING:
// Start to fade in
mAlphaRate = 0;
fade(0);
break;
case STATE_SHOWN:
// Cancel any fade effect
mHandler.removeMessages(0);
break;
case STATE_HIDING:
// Start to fade out after three seconds
mAlphaRate = 1;
fade(3000);
break;
}
}
private boolean contains(float x, float y) {
// Determine if the point is in index bar region, which includes the right margin of the bar
return (x >= mIndexbarRect.left && y >= mIndexbarRect.top && y <= mIndexbarRect.top + mIndexbarRect.height());
}
private int getSectionByPoint(float y) {
if (mSections == null || mSections.length == 0)
return 0;
if (y < mIndexbarRect.top + mIndexbarMargin)
return 0;
if (y >= mIndexbarRect.top + mIndexbarRect.height() - mIndexbarMargin)
return mSections.length - 1;
return (int) ((y - mIndexbarRect.top - mIndexbarMargin) / ((mIndexbarRect.height() - 2 * mIndexbarMargin) / mSections.length));
}
private void fade(long delay) {
mHandler.removeMessages(0);
mHandler.sendEmptyMessageAtTime(0, SystemClock.uptimeMillis() + delay);
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (mState) {
case STATE_SHOWING:
// Fade in effect
mAlphaRate += (1 - mAlphaRate) * 0.2;
if (mAlphaRate > 0.9) {
mAlphaRate = 1;
setState(STATE_SHOWN);
}
mListView.invalidate();
fade(10);
break;
case STATE_SHOWN:
// If no action, hide automatically
setState(STATE_HIDING);
break;
case STATE_HIDING:
// Fade out effect
mAlphaRate -= mAlphaRate * 0.2;
if (mAlphaRate < 0.1) {
mAlphaRate = 0;
setState(STATE_HIDDEN);
}
mListView.invalidate();
fade(10);
break;
}
}
};
}
if i add this it works code in mainactivity
listView = (ListView) findViewById(R.id.homelistView);
your are using a custom ListView class, com.woozzu.android.widget.IndexableListView
You have to replace your "ListView " in layout file to a "com.woozzu.android.widget.IndexableListView"
Change your Layout to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#ff3344"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:layout_alignTop="#+id/scrollView1"
android:layout_toRightOf="#+id/scrollView1" >
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
The solution Suggested by #Anis is the only working solution I found. In addition to that, If you want Click listeners to components on your List View Items, you have to update the Code as mentioned here, https://github.com/denley/IndexableListView/commit/18210a54487ba079bb332fafec709e2de26883db
I am making an android game that is checking the players health value when this method is being runned. But however, it's not reacting. It doesn't do anything, when the value is less than 3, it shouldn't do anything, but when it is equal to 3, it should run a method. Please help me and thanks SO much in advance! This is the code that i am using:
private void checkLivesLeftValue() {
if (livesLeftValue == 3) {
//Message to display: "You lost!
onMethod();
}
else {
livesLeftValue = livesLeftValue + 1;
}
}
Full code:
package com.mysoftwaremobileapps.ParachuteHunter;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.TextView;
import android.widget.Toast;
public class ExampleView extends SurfaceView implements SurfaceHolder.Callback
{
class ExampleThread extends Thread
{
private ArrayList<Parachuter> parachuters;
private Bitmap parachuter;
private Paint black;
private boolean running;
private SurfaceHolder mSurfaceHolder;
private Context mContext;
private Handler mHandler;
private GameScreenActivity mActivity;
private long frameRate;
private boolean loading;
public float x;
public float y;
public MediaPlayer mp1;
public int parachuterIndexToResetAndDelete;
public int canvasGetWidth;
public int livesLeftValue;
public ExampleThread(SurfaceHolder sHolder, Context context, Handler handler)
{
mSurfaceHolder = sHolder;
mHandler = handler;
mContext = context;
mActivity = (GameScreenActivity) context;
parachuters = new ArrayList<Parachuter>();
parachuter = BitmapFactory.decodeResource(getResources(), R.drawable.parachuteman);
black = new Paint();
black.setStyle(Paint.Style.FILL);
black.setColor(Color.WHITE);
running = true;
// This equates to 26 frames per second.
frameRate = (long) (1000 / 26);
loading = true;
}
#Override
public void run()
{
while (running)
{
Canvas c = null;
try
{
c = mSurfaceHolder.lockCanvas();
synchronized (mSurfaceHolder)
{
long start = System.currentTimeMillis();
doDraw(c);
long diff = System.currentTimeMillis() - start;
if (diff < frameRate)
Thread.sleep(frameRate - diff);
}
} catch (InterruptedException e)
{
}
finally
{
if (c != null)
{
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
protected void doDraw(Canvas canvas)
{
canvas.drawRect(0, 0, canvas.getWidth(), canvas.getHeight(), black);
canvasGetWidth = canvas.getWidth();
//Draw
for (int i = 0; i < parachuters.size(); i++)
{
canvas.drawBitmap(parachuter, parachuters.get(i).getX(), parachuters.get(i).getY(), null);
parachuters.get(i).tick();
}
//Remove
for (int i = 0; i < parachuters.size(); i++)
{
if (parachuters.get(i).getY() > canvas.getHeight()) {
parachuters.remove(i);
onPlaySound();
checkLivesLeftValue();
}
}
}
public void onPlaySound()
{
try {
mp1 = MediaPlayer.create(getContext(), R.raw.bombsound);
mp1.start();
} catch (Exception e) {
e.printStackTrace();
mp1.release();
}
}
public void onMethod() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "You lost!", 15).show();
}
});
}
private void checkLivesLeftValue() {
// TODO Auto-generated method stub
if (livesLeftValue == 3) {
//Message to display: "You lost!
onMethod();
}
else {
livesLeftValue = livesLeftValue + 1;
}
}
public boolean onTouchEvent(MotionEvent event)
{
if (event.getAction() != MotionEvent.ACTION_DOWN)
return false;
float x1 = event.getX();
float y1 = event.getY();
initiateDrawParachuters();
return true;
}
public void initiateDrawParachuters()
{
drawParachuter1();
}
private void drawParachuter1() {
// TODO Auto-generated method stub
//Parachuter nr. 1
x = 68;
y = 40;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter2();
}
private void drawParachuter2() {
// TODO Auto-generated method stub
//Parachuter nr. 2
x = 100;
y = 80;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter3();
}
private void drawParachuter3() {
// TODO Auto-generated method stub
//Parachuter nr. 3
x = 150;
y = 120;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter4();
}
private void drawParachuter4() {
// TODO Auto-generated method stub
//Parachuter nr. 4
x = 170;
y = 150;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter5();
}
private void drawParachuter5() {
// TODO Auto-generated method stub
//Parachuter nr. 5
x = 180;
y = 170;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
drawParachuter6();
}
private void drawParachuter6() {
// TODO Auto-generated method stub
//Parachuter nr. 6
x = 200;
y = 180;
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
}
public void drawParachuters()
{
Parachuter p = new Parachuter(x, y);
parachuters.add(p);
Toast.makeText(getContext(), "x=" + x + " y=" + y, 15).show();
}
public void setRunning(boolean bRun)
{
running = bRun;
}
public boolean getRunning()
{
return running;
}
}
/** Handle to the application context, used to e.g. fetch Drawables. */
private Context mContext;
/** Pointer to the text view to display "Paused.." etc. */
private TextView mStatusText;
/** The thread that actually draws the animation */
private ExampleThread eThread;
public ExampleView(Context context)
{
super(context);
// register our interest in hearing about changes to our surface
SurfaceHolder holder = getHolder();
holder.addCallback(this);
// create thread only; it's started in surfaceCreated()
eThread = new ExampleThread(holder, context, new Handler()
{
#Override
public void handleMessage(Message m)
{
// mStatusText.setVisibility(m.getData().getInt("viz"));
// mStatusText.setText(m.getData().getString("text"));
}
});
setFocusable(true);
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
return eThread.onTouchEvent(event);
}
public ExampleThread getThread()
{
return eThread;
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder)
{
if (eThread.getState() == Thread.State.TERMINATED)
{
eThread = new ExampleThread(getHolder(), getContext(), getHandler());
eThread.start();
}
else
{
eThread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder)
{
boolean retry = true;
eThread.setRunning(false);
while (retry)
{
try
{
eThread.join();
retry = false;
}
catch (InterruptedException e)
{
}
}
}
}
I agree with the others, check the value via Log messages, so you can see the actual values.
Also, check if it might go over 3. I dont know what kind of game you are making but for example, say that livesLeftValue=2 for now, but something happens, and it increases by 2, reaching 4, without ever having the value 3. Lets say it never gets decreased, so you will never ever hit the value 3, thus never invoking the game over thingie, and livesLeftValue will just increase to the infinity.
put some debug in there and see if you really get the right value in here.
private void checkLivesLeftValue() {
Log.d("checkLivesLeftValue", "lives = " + livesLeftValue);
if (livesLeftValue == 3) {
Log.d("checkLivesLeftValue", "calling onMethod now");
onMethod();
} else {
livesLeftValue = livesLeftValue + 1;
Log.d("checkLivesLeftValue", "increased lives to " + livesLeftValue);
}
}
public void onMethod() {
Log.d("onMethod", "in onMethod");
mHandler.post(new Runnable() {
#Override
public void run() {
Log.d("onMethod", "showing Toast now");
Toast.makeText(getContext(), "You lost!", 15).show();
}
});
}