In my app I want to randomly pick an image and put it in the center of the screen. After that, animations can be performed, the image will be moved and reset to its origin position afterwards. Then I want to choose a new image of the switch case, but the image always stays the same. How can I fix it?
public class MainActivity extends Activity implements OnGestureListener
{
private ImageView imageView;
float x1,x2;
float y1, y2;
public int sco = 0;
TextView score;
final Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageview1);
imageView.setImageResource(getMyRandomResId());
score = (TextView)findViewById(R.id.textView2);
}
int imag = rand.nextInt(4);
int getMyRandomResId() {
switch (imag) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
default:
return R.drawable.d;
}
}
private boolean animationRunning = false;
public boolean onTouchEvent(MotionEvent touchevent)
{
final ViewPropertyAnimator animator = imageView.animate();
switch (touchevent.getAction())
{
case MotionEvent.ACTION_DOWN:
{
x1 = touchevent.getX();
y1 = touchevent.getY();
break;
}
case MotionEvent.ACTION_UP:
{
x2 = touchevent.getX();
y2 = touchevent.getY();
if (!animationRunning) {
//left to right sweep event on screen
if (x1 < x2 && (x2-x1)>=(y1-y2) && (x2-x1)>=(y2-y1)) {
animationRunning = true;
animator.translationX(imageView.getWidth() * 2)
.setDuration(180)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
if(getMyRandomResId() == R.drawable.ballgrue) {
sco++;
}
imageView.setTranslationX(0);
imageView.setImageResource(getMyRandomResId());
animationRunning = false;
}
})
.start();
}
}
}
}
}
}
int getMyRandomResId() {
int imag = rand.nextInt(4);
switch (imag) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
default:
return R.drawable.d;
}
}
the reason you got a same image bcoz of this only
Hope it helps
Related
I was working on a game on Android studio where user touch drives tiles to combine. To do this, I have used a GridLayout separated into rows and columns. The value is displayed with imageview and all gridlayout cells are linked to a separate cell class which includes imageview ID's. I implemented a listener on each image view to detect when a swiping motion occured. The code for initalizing the board and listeners is below:
for(int i = 0; i<noOfBlocks; i++) {
for (int j = 0; j < noOfBlocks; j++) {
ImageView imageView = new ImageView(this);
imageView.setId(iDcnt);
imageView.setLayoutParams(new ViewGroup.LayoutParams(widthOfBlock, widthOfBlock));
imageView.setMaxHeight(widthOfBlock);
imageView.setMaxWidth(widthOfBlock);
int randomNum = (int) Math.floor(random.nextDouble() * gamepiece.length);
imageView.setImageResource(gamepiece[randomNum]);
Cell c = new Cell(i + 1, j+1, randomNum, imageView.getId());
imageView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
SquarePlay s = null;
try {
s = new SquarePlay();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
s.onSwipeEvent(event);
return false;
}
});
gameBoard.addView(imageView);
iDcnt++;
}
The OnTouch events are handled in a separate class in the method which is shown below:
float x1, x2, y1, y2, dx, dy;
public void onSwipeEvent(MotionEvent event){
switch(event.getAction()) {
case(MotionEvent.ACTION_DOWN):
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0)
onSwipeRight();
else
onSwipeLeft();
} else {
if(dy>0)
onSwipeDown();
else
onSwipeUp();
}
}
}
}
private void onSwipeLeft() {
System.exit(0);
}
private void onSwipeRight() {
System.exit(0);
}
private void onSwipeUp() {
System.exit(0);
}
private void onSwipeDown() {
System.exit(0);
}
NOTE:System.exit is just there to test if this works.
The App loads but does not produce a response from the swipe events, Does anyone have any suggestions on how to resolve this issue?
Thank you :)
To use swipe You can create your class inside the activity class as follow##
declare the class name inside the activity class
SwipeListener swipeListener;
inside the activity class write this code to handle the swipe##
private class SwipeListener implements View.OnTouchListener {
//create gesture detector variable
GestureDetector gestureDetector;
//create constructor
SwipeListener(View view){
int threshold = 100;
int velocity_threshold = 100;
GestureDetector.SimpleOnGestureListener listener =
new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onDown(MotionEvent e) {
return super.onDown(e);
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//get x and y difference
float xDiff = e2.getX() - e1.getX();
float yDiff = e2.getY() - e1.getY();
try {
if(Math.abs(xDiff)>Math.abs(yDiff)){
if(Math.abs(xDiff)>threshold &&
Math.abs(velocityX)> velocity_threshold){
if(xDiff > 0){
//swipe right
Intent intent = new Intent(TopUpBalance.this, HomePage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}else{
//swipe left
}
return true;
}//you can handle swipe down and above here as well, the same way above
}
}catch (Exception e){
e.printStackTrace();
}
return false;
}
};
//init gesture
gestureDetector = new GestureDetector(listener);
view.setOnTouchListener(this);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return gestureDetector.onTouchEvent(motionEvent);
}
}
Declare your SwipeListener onCreate method as follow##
linearLayout = findViewById(R.id.layoutID);
//swipe
swipeListener = new SwipeListener(linearLayout);
I Have tried with all possible ways which is suggested in StackOverflow
But i can't able to change from click to drag
OnTouch event is used for click.. and my images get clicked in this. and i can't able to drag and drop the image. i need to drag the image instead of clicking...
I will be much thankful to you. if you help me on this part
i have also tried this scenario's
Drag and Drop and OnClick TextView
But i didn't get any result. so please can anyone help me!!!!!!!
Can anyone help me in this ??
public class TouchListener implements View.OnTouchListener {
private float xDelta;
private float yDelta;
private PuzzleActivity activity;
public TouchListener(PuzzleActivity activity) {
this.activity = activity;
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
float x = motionEvent.getRawX();
float y = motionEvent.getRawY();
final double tolerance = sqrt(pow(view.getWidth(), 2) + pow(view.getHeight(), 2)) / 10;
PuzzlePiece piece = (PuzzlePiece) view;
if (!piece.canMove) {
return true;
}
RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
switch (motionEvent.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
xDelta = x - lParams.leftMargin;
yDelta = y - lParams.topMargin;
piece.bringToFront();
break;
case MotionEvent.ACTION_MOVE:
lParams.leftMargin = (int) (x - xDelta);
lParams.topMargin = (int) (y - yDelta);
view.setLayoutParams(lParams);
break;
case MotionEvent.ACTION_UP:
int xDiff = abs(piece.xCoord - lParams.leftMargin);
int yDiff = abs(piece.yCoord - lParams.topMargin);
if (xDiff <= tolerance && yDiff <= tolerance) {
lParams.leftMargin = piece.xCoord;
lParams.topMargin = piece.yCoord;
piece.setLayoutParams(lParams);
piece.canMove = false;
sendViewToBack(piece);
activity.checkGameOver();
}
break;
}
return true;
}
public void sendViewToBack(final View child) {
final ViewGroup parent = (ViewGroup)child.getParent();
if (null != parent) {
parent.removeView(child);
parent.addView(child, 0);
}
}
}
Just like how those conveyors in some apps that you can swipe to the right to bring out (show it) and then swipe to the left to send back in, hiding it again. I tried using setOnTouchListener again on the same view with a delayed message after it's brought out, but the app receives an error and closes when you try to bring it out (show). If I am to remove the method that is supposed to make it go back in (hidden), it would be brought out just fine, but how do I make it happen that it could be sent back in and hidden through swiping to the left after it's been brought out by swiping to the right?
Here's the code I used in the activity:
ImageView conveyorWheel;
private float x1, x2;
static final int MIN_DISTANCE = 150;
RelativeLayout parentLayout;
android.os.Handler conveyorHandler;
conveyorWheel = (ImageView) findViewById(R.id.conveyerWheel);
parentLayout = (RelativeLayout) findViewById(R.id.parentLayout);
protected void onCreate(Bundle savedInstanceState) {
...
parentLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_MOVE:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE & x1 < x2) {
conveyorWheel.animate()
.x(-750)
.setDuration(150)
.start();
conveyorHandler.postDelayed(new Runnable() {
#Override
public void run() {
conveyorRevert();
}
}, 151);
break;
}
default:
return false;
}
return true;
}
});
}
private void conveyorRevert (){
parentLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
x1 = event.getX();
break;
case MotionEvent.ACTION_MOVE:
x2 = event.getX();
float deltaX = x2 - x1;
if (Math.abs(deltaX) > MIN_DISTANCE){
conveyorWheel.animate()
.x(-950)
.setDuration(150)
.start();
break;
}
default: return false;
}
return true;
}
});
}
The Android Monitor displayed the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Handler.postDelayed(java.lang.Runnable, long)' on a null object reference
But I have no idea how to fix this
I am using horizontal scrollview, and when I am clicking on the image buttom of horizontal scrollview, then my image is showing in the imageview. This functionality is working properly.
And in the image view I am able to zoom the image. But after zooming, when I am clicking on the next image button of scrollview then, imageview bydefault showing zoomed image. Actually it is taking zoom of previous image. So my problem is that how can I remove previous zoom, for next image. I mean next image must come with default size, not already zoomed.
Here is my code.
public class ViewButtonActivity extends Activity implements OnClickListener,
OnTouchListener {
ImageView imgView;
private ProgressDialog pDialog;
public static boolean isTouch = false;
ImageButton imgButton1, imgButton2, imgButton3, imgButton4, imgButton5;
HorizontalScrollView horizontalScrollView;
public ImageLoader imageLoader;
public static String[] imageUrl = {
"http://0-03/_cover.jpg",
"http://www.magazine.jpg",
"http://large_1.jpg",
"http://4.bp.Apr2011.jpg",
"http://www.theof.com/git.jpg" };
private int mImageHeight, mImageWidth;
private static final String TAG = "Touch";
private static final float MIN_ZOOM = 1f, MAX_ZOOM = 1f;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_button_click_activity);
imageLoader = new ImageLoader(getApplicationContext());
imgView = (ImageView) findViewById(R.id.image_view);
imgButton1 = (ImageButton) findViewById(R.id.imageButton1);
imgButton2 = (ImageButton) findViewById(R.id.imageButton2);
imgButton3 = (ImageButton) findViewById(R.id.imageButton3);
imgButton4 = (ImageButton) findViewById(R.id.imageButton4);
imgButton5 = (ImageButton) findViewById(R.id.imageButton5);
horizontalScrollView = (HorizontalScrollView) findViewById(R.id.horizontal_scroll_view);
imageLoader.DisplayImage(imageUrl[0], imgButton1);
imageLoader.DisplayImage(imageUrl[1], imgButton2);
imageLoader.DisplayImage(imageUrl[2], imgButton3);
imageLoader.DisplayImage(imageUrl[3], imgButton4);
imageLoader.DisplayImage(imageUrl[4], imgButton5);
imgButton1.setOnClickListener(this);
imgButton2.setOnClickListener(this);
imgButton3.setOnClickListener(this);
imgButton4.setOnClickListener(this);
imgButton5.setOnClickListener(this);
mImageHeight = imgView.getWidth();
mImageWidth = imgView.getHeight();
imgView.setOnTouchListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
imageLoader.DisplayImage(imageUrl[0], imgView);
break;
case R.id.imageButton2:
imageLoader.DisplayImage(imageUrl[1], imgView);
break;
case R.id.imageButton3:
imageLoader.DisplayImage(imageUrl[2], imgView);
break;
case R.id.imageButton4:
imageLoader.DisplayImage(imageUrl[3], imgView);
break;
case R.id.imageButton5:
imageLoader.DisplayImage(imageUrl[4], imgView);
// imgView.setImageResource(R.drawable.img5);
break;
}
}
public boolean onTouch(View v, MotionEvent event) {
ImageView imgView = (ImageView) v;
imgView.setScaleType(ImageView.ScaleType.MATRIX);
float scale;
dumpEvent(event);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // first finger down only
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG"); // write to LogCat
mode = DRAG;
break;
case MotionEvent.ACTION_UP: // first finger lifted
case MotionEvent.ACTION_POINTER_UP: // second finger lifted
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_POINTER_DOWN: // first and second finger down
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 5f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY()
- start.y); // create the transformation in the matrix
// of points
} else if (mode == ZOOM) {
// pinch zooming
float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 5f) {
matrix.set(savedMatrix);
scale = newDist / oldDist; // setting the scaling of the
// matrix...if scale > 1 means
// zoom in...if scale < 1 means
// zoom out
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
imgView.setImageMatrix(matrix);
return true;
}
private float spacing(MotionEvent event)
{
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event)
{
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
private void dumpEvent(MotionEvent event)
{
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE","POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP)
{
sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++)
{
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d("Touch Events ---------", sb.toString());
}
}
Presumably you have to reset to the original value of the Matrix which contains the current state of the transformation (which includes zoom)? I see you already keep track of the Matrix, what's standing in your way resetting it to the old value when you advance to the next image during onClick()?
I have a problem with my activity which showing CUBE 3D (simple OpenGL example). When I pressing back key on my phone or emulator, it should return to main menu, but instead of returning nothing happens. Any clue?
Here's the code:
public class Graphic3D extends Activity {
private GLSurfaceView glView; // Use subclass of GLSurfaceView (NEW)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Allocate a custom subclass of GLSurfaceView (NEW)
glView = new MyGLSurfaceView(this);
setContentView(glView); // Set View (NEW)
}
#Override
public void onBackPressed() {
super.onBackPressed();
// ????????
}
#Override
protected void onPause() {
super.onPause();
glView.onPause();
}
#Override
protected void onResume() {
super.onResume();
glView.onResume();
}
}
MySurfaceView class:
public class MyGLSurfaceView extends GLSurfaceView {
Graphics3DRenderer renderer; // Custom GL Renderer
// For touch event
private final float TOUCH_SCALE_FACTOR = 180.0f / 320.0f;
private float previousX;
private float previousY;
// Constructor - Allocate and set the renderer
public MyGLSurfaceView(Context context) {
super(context);
renderer = new Graphics3DRenderer(context);
this.setRenderer(renderer);
// Request focus, otherwise key/button won't react
this.requestFocus();
this.setFocusableInTouchMode(true);
}
// Handler for key event
#Override
public boolean onKeyDown(int keyCode, KeyEvent evt) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: // Decrease Y-rotational speed
renderer.speedY -= 0.3f;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT: // Increase Y-rotational speed
renderer.speedY += 0.3f;
break;
case KeyEvent.KEYCODE_DPAD_UP: // Decrease X-rotational speed
renderer.speedX -= 0.3f;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: // Increase X-rotational speed
renderer.speedX += 0.3f;
break;
case KeyEvent.KEYCODE_VOLUME_DOWN:// Zoom out (decrease z)
renderer.z -= 0.4f;
break;
case KeyEvent.KEYCODE_VOLUME_UP: // Zoom in (increase z)
renderer.z += 0.4f;
break;
case KeyEvent.KEYCODE_DPAD_CENTER:
renderer.speedY = 0;
renderer.speedX = 0;
renderer.z = -6.0f;
break;
}
return true; // Event handled
}
// Handler for touch event
#Override
public boolean onTouchEvent(final MotionEvent evt) {
float currentX = evt.getX();
float currentY = evt.getY();
float deltaX, deltaY;
switch (evt.getAction()) {
case MotionEvent.ACTION_MOVE:
// Modify rotational angles according to movement
deltaX = currentX - previousX;
deltaY = currentY - previousY;
renderer.angleX += deltaY * TOUCH_SCALE_FACTOR;
renderer.angleY += deltaX * TOUCH_SCALE_FACTOR;
}
// Save current x, y
previousX = currentX;
previousY = currentY;
return true; // Event handled
}
}
In an Activity, calling finish() will close the current Activity. If you haven't closed the main menu Activity, it should "open" itself.
If you need to start an Activity again, for example if your menu Activity is closed, you can do the following.
Intent i = new Intent(getApplicationContext(), Menu.class);
startActivity(i);
finish();