How to operate Android OS with screen coordinates - android

I have coordinates of screen and I want to tell operating system to perform that operation which OS is supposed to perform on touch of screen on that coordinates.
Just like cicret somehow tells mobile phone that what to do. While user is not directly interacting with mobile phone.
Plz tell me anything if you know about it.

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
public class MainActivity extends Activity
{
StringBuilder stringBuilder = new StringBuilder();
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textView = (TextView) findViewById( R.id.strXY );
this.textView.setText("X: ,Y: ");//texto inicial
this.textView.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
stringBuilder.setLength(0);
if (arg1.getAction() == MotionEvent.ACTION_MOVE) {
stringBuilder.append("Moving, X:" + arg1.getX() + ", Y:" + arg1.getY());
}
else {
stringBuilder.append("Stoped, X:" + arg1.getX() + ", Y:" + arg1.getY());
}
textView.setText(stringBuilder.toString());
return true;
}
});
}
}

Related

onTouchEvent() method gets called over 7 times

Just got into Android development.. Please bear with me.
I created an overridden onTouchEvent function. Every time I touch somewhere inside my app, I expect it to run the function twice. Instead, the function runs random number of times. Some times 7, other times 12. I am just wondering if this is normal?
This is my code if anyone is curious..
package com.jojocoder.subhunter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.view.Display;
import android.util.Log;
import android.widget.ImageView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int numberHorizontalPixels;
int numberVerticalPixels;
int blockSize;
int gridWidth = 40;
int gridHeight;
float horizantalTouched = -100;
float verticalTouched = -100;
int subHorizaltalPosition;
int subVerticalPosition;
boolean hit = false;
int shotsTaken;
int distanceFromSub;
boolean debugging = true;
int testcount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
numberHorizontalPixels = size.x;
numberVerticalPixels = size.y;
blockSize = numberHorizontalPixels / gridWidth;
gridHeight = numberVerticalPixels / blockSize;
Log.d("Debugging","Running OnCreate func");
newGame();
draw();
}
public void newGame() {
Log.d("Debugging", "Running newGame func");
}
void draw() {
Log.d("Debugging", "Running draw func");
printDebuggingText();
}
#Override
public boolean onTouchEvent(MotionEvent motionEvent) {
testcount ++;
Log.d("Debugging", "Running OnTouchEvent func");
takeShot();
return true;
}
void takeShot() {
Log.d("Debugging", "Running takeShot func");
draw();
}
void boom() {
}
void printDebuggingText() {
Log.d("numberHorizantalPixels", "" + numberHorizontalPixels);
Log.d("numberVerticalPixels", "" + numberVerticalPixels);
Log.d("blockSize", "" + blockSize);
Log.d("gridWidth", "" + gridWidth);
Log.d("gridHeight", "" + gridHeight);
Log.d("horizantalTouched", "" + horizantalTouched);
Log.d("verticalTouhced", "" + verticalTouched);
Log.d("subHorizantalPosition", "" + subHorizaltalPosition);
Log.d("subVerticalPosition", "" + subVerticalPosition);
Log.d("hit", "" + hit);
Log.d("shotsTaken", "" + shotsTaken);
Log.d("debugging", "" + debugging);
Log.d("distanceFronSub", "" + distanceFromSub);
Log.d("testcount", "" + testcount);
}
}
Thanks in advance.
If you are using onTouchEvent() method to intercept the touch events in an Activity or a View. This method is called several times as the pressure, size, position, etc. of the touch event changes or even when a new finger is put on the touch screen.

Calling custom view from main activity.. Message in onDraw() is printed but custom view is not rendered

I have two classes - MainActivity.java and MainView.java.
I'm trying to render a custom view (defined in MainView.java) when screen is touched from the main activity.
My code is doing a funky thing. From the main page, when you touch the screen, it does NOT render the custom view I've specified in MainView.java - but still prints out a message I put in the onDraw() method, which should mean that onDraw() is being run. Why is my onDraw() method being run but its view doesn't render?
Also, both my onTouchEvent in MainActivity.java and MainView.java seems to respond at the same time, although the view I see is the only the activity_main.xml.
Please help :(
MainActivity.java
package com.example.owner.thesisapp;
import com.example.owner.thesisapp.MainView;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.media.AudioManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.media.SoundPool;
import android.view.View;
import android.graphics.Canvas;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity {
private static SoundPool soundPool;
private static HashMap soundPoolMap;
private static int S1 = R.raw.a3v1;
private static int S2 = R.raw.c3v1;
private static int S3 = R.raw.dsharp3v1;
private static int S4 = R.raw.fsharp3v1;
private int soundID;
private boolean isSoundLoaded = false;
public MainView mainView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainView = (MainView) findViewById(R.id.main_view);
soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId,
int status) {
isSoundLoaded = true;
}
});
soundID = soundPool.load(this, R.raw.fsharp3v1, 1);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
if (isSoundLoaded) {
soundPool.play(soundID, 1f, 1f, 1, 0, 1f);
Log.d("Test", "Played sound");
}
mainView.postInvalidate();
return false;
}
#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_main, menu);
return true;
}
#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
// Keep landscape orientation
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
}
MainView.java
package com.example.owner.thesisapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
/**
* Created by Owner on 6/1/2015.
*/
public class MainView extends View {
Bitmap stillWave;
int iy = 0;
public MainView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
stillWave = BitmapFactory.decodeResource(getResources(), R.drawable.wave);
setWillNotDraw(false);
Log.d("MAINVIEW: Is this ran?", " ");
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int)event.getX();
int y = (int)event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("Action DOWN!", " ");
iy = 0;
this.invalidate();
case MotionEvent.ACTION_MOVE:
Log.d("Action MOVE!", " ");
case MotionEvent.ACTION_UP:
Log.d("Action UP!", " ");
}
return false;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("MAINVIEW ONDRAW: Is this ran?", " ");
int width = canvas.getWidth();
int height = canvas.getHeight();
//set background
Rect wBackground = new Rect();
wBackground.set(0, 0, width, height);
Paint pBackground = new Paint();
pBackground.setStyle(Paint.Style.FILL);
pBackground.setColor(Color.BLACK);
canvas.drawRect(wBackground, pBackground);
//Log.d("garo, sero", width + " " + height);
//set Wave
Paint pWave = new Paint();
pWave.setStyle(Paint.Style.FILL_AND_STROKE);
pWave.setColor(Color.WHITE);
pWave.setStrokeWidth(10);
pWave.setStrokeCap(Paint.Cap.ROUND);
int waveFlucMin = -100;
int waveFlucMax = 100;
float[] coords = new float[width * 2];
for (int ix = 0; ix < width; ix++) {
int yoffset = waveFlucMin + (int) (Math.random() * ((waveFlucMax - waveFlucMin) + 1));
coords[2 * ix] = (float) ix;
coords[2 * ix + 1] = (float) iy + yoffset;
}
//Log.d("Coordinates x?", coords[1] + " " + coords[3] + " " + coords[5] + " " + coords[7] + " " + coords[301] + " " + coords[303] + " ");
//Log.d("Coordinates y?", coords[0] + " " + coords[2] + " " + coords[4] + " " + coords[6] + " " + coords[300] + " " + coords[302] + " ");
//Log.d("Generating?", "YES, generating forloop : " + iy);
//wait a second between each wave generation
/*
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
drawWave(coords, width, pWave, canvas);
if (iy < height) {
iy += 10;
invalidate();
} else {
//do nothing - finish onDraw() call.
}
}
private void drawWave(float[] coords, int width, Paint pWave, Canvas canvas) {
canvas.drawPoints(coords, 0, width*2, pWave);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<com.example.owner.thesisapp.MainView
android:id="#+id/main_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#111C64"/>
The problem is in your layout. Both your custom View and the ImagView are, since your are using a RelativeLayout, aligned to the Top left. The z order in this case put the ImageView on top on your custom View and, since it is taking the whole screen, you can't see your custom view.

draw a line on an image (ImageView)

I have an app that shows an image (ImageView). I want that when I touch the screen on the image, it draws a line in the same point where I touched.
With this code I can't do it but i think that it has a logical thought.
Could you help me please?
Thanks
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.Toast;
public class Cronograma extends Activity{
public boolean touched=false;
public float touched_x=0, touched_y=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cronograma);
}
public void onDraw(Canvas canvas){
Paint pincel = new Paint();
pincel.setColor(Color.BLUE);
pincel.setStrokeWidth(8);
pincel.setStyle(Style.STROKE);
if (touched==true)
canvas.drawLine(touched_x, touched_y, touched_x+5, touched_y, pincel);
}
public boolean onTouchEvent (MotionEvent event){
touched_x = event.getX();
touched_y = event.getY();
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
Toast toast = Toast.makeText(getApplicationContext(), "La coordenada x es " + touched_x + " y la coordenada y es " + touched_y , Toast.LENGTH_SHORT);
toast.show();
touched=true;
break;
}
return false;
}
}

Full Screen Gallery Code

i just find some solution for an full screen gallery implementation but i cant get the code work. maybe anyone can help me about that.
I need a full screen image switcher without an thumbnail gallery where i can switch between the pictures with swiping with finger.
i got the following error:
firstActivity cannot be resolved to a type
slide_in_right cannot be resolved or is not a field
slide_out_left cannot be resolved or is not a field
i am pretty new to android coding :)
Please help me
package com.example.prog;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ViewSwitcher;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.view.Window;
import android.content.Context;
public class l2_AltInvestActivity extends Activity implements ViewFactory {
ImageSwitcher imageSwitcher;
Integer[] imageList = {
R.drawable.fr_l1_01,
R.drawable.fr_l1_02,
R.drawable.fr_l1_03,
R.drawable.fr_l1_04,
R.drawable.fr_l1_05
};
int curIndex=0;
int downX, upX;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mmenutest);
imageSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
imageSwitcher.setFactory(this);
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
imageSwitcher.setImageResource(imageList[curIndex]);
imageSwitcher.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
downX = (int) event.getX();
Log.i("event.getX()", " downX " + downX);
return true;
}
else if (event.getAction() == MotionEvent.ACTION_UP) {
upX = (int) event.getX();
Log.i("event.getX()", " upX " + downX);
if (upX - downX > 100) {
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(firstActivity.this,android.R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(firstActivity.this,android.R.anim.slide_out_right));
//curIndex current image index in array viewed by user
curIndex--;
if (curIndex < 0) {
curIndex = 5; //maximum
}
//imageList :-image list array
imageSwitcher.setImageResource(imageList[curIndex]);
//GalleryActivity.this.setTitle(curIndex);
}
else if (downX -upX > -100) {
curIndex++;
if (curIndex > 4) {
curIndex = 0;
}
imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_in_right));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.slide_out_left));
imageSwitcher.setImageResource(imageList[curIndex]);
//GalleryActivity.this.setTitle(curIndex);
}
return true;
}
return false;
}
});
} //END onCreate
#Override
public View makeView() {
ImageView i = new ImageView(this);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
i.setBackgroundColor(0xFF000000);
return i;
} //END makeView
} // END Class
Use Current Activity Context to access resources instead of Any other activity as in current code you are trying to access Animation resources by passing firstActivity.this .
imageSwitcher.setInAnimation(AnimationUtils.
loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_in_left));
imageSwitcher.setOutAnimation(AnimationUtils.
loadAnimation(l2_AltInvestActivity.this,android.R.anim.slide_out_right));
use l2_AltInvestActivity.this instead of firstActivity.this

android animation when user touch on a image it has to animate gif file

I'm developing an application,in this when user touch on a image he will see an animated image for a while and come back to original image .
I'm able to animate gif file ,but the animation is running repeatedly , how to restrict animation, once the animation completes and comes back to image view
please anybody help me regarding this,
thanks in advance
here is my code
package purpletalk.gifanimation;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Movie;
import android.graphics.Point;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.view.View.OnTouchListener;
import android.view.animation.OvershootInterpolator;
public class GifAnimationDemo extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
ImageView image;
static int i=0;
AnimationDrawable rocketAnimation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println("\tmoviestart121321="+i);
image=(ImageView)findViewById(R.id.imageView1);
image.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
/*image.setBackgroundResource(R.drawable.babyanim);
rocketAnimation = (AnimationDrawable)image.getBackground();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
rocketAnimation.start();
rocketAnimation.isOneShot();
return true;
}
*/
if (event.getAction() == MotionEvent.ACTION_DOWN) {
setContentView(new GIFView(this));
}
else
{setContentView(R.layout.main);
}
return false;
}
class GIFView extends View {
Movie movie;
InputStream is=null;
long moviestart;
private long startTime;
private long endTime;
private long duration=100000;
public GIFView(Context context) {
super(context);
is=context.getResources().openRawResource(R.drawable.baby1);
movie=Movie.decodeStream(is);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFCCCCCC);
super.onDraw(canvas);
//long now=android.os.SystemClock.uptimeMillis();
long curTime = System.currentTimeMillis();
// float percentTime = (float) (curTime - startTime)
// (float) (endTime - startTime);
//System.out.println("now="+now);
// first time
moviestart = 0;
System.out.println("\tmoviestart="+i);
int relTime = (int)((curTime - moviestart) % movie.duration()) ;
// System.out.println("time="+relTime+"\treltime="+movie.duration());
// movie.setTime((int) (now+movie.duration()));
// movie.duration();
movie.setTime(relTime);
movie.draw(canvas,20,20);
this.invalidate();
}
#Override
protected void onAnimationEnd() {
// TODO Auto-generated method stub
Log.e("Animation end","time");
super.onAnimationEnd();
}
public void onAnimateMove(float dx, float dy, long duration) {
startTime = System.currentTimeMillis();
endTime = startTime + duration;
}
}
}

Categories

Resources