GestureOverlayView not working - android

I am kind of puzzeld right now :
I created 4 gestures using the Gesturebuilder
1 Gesture is a swipe pointing up
2 Gesture is a swipe pointing down
3 Gesture is a swipe pointing left
4 Gesture is a swipe pointing right
but when I try to make a gesture on the running app
only left and right is recognized but also it seams like up and down are the same like left and right
because the method gives me the getsures as a toat
the toast for swiping left shows : up,left
I am also using a custom view in my activity and a OntouchListener but I can't get it to work
Activity :
public class RunActivity extends Activity implements OnTouchListener, OnGesturePerformedListener {
static int width;
static int height;
static boolean reset=false;
draw d;
//jump
private GestureLibrary gestureLib;
private static Context mContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
d = new draw(this);
d.setOnTouchListener(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mContext = this;
//get screen size
WindowManager wm = (WindowManager) this.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
width = display.getWidth(); // deprecated
height = display.getHeight(); // deprecated
//Jump
GestureOverlayView gestureOverlayView = new GestureOverlayView(this);
View inflate = d;
gestureOverlayView.addView(inflate);
gestureOverlayView.addOnGesturePerformedListener(this);
gestureLib = GestureLibraries.fromRawResource(this, R.raw.gestures);
if (!gestureLib.load()) {
finish();
}
setContentView(gestureOverlayView);
//setContentView(d);
}
public static Context getContext(){
return mContext;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("touch","touched");
if (draw.end == true)
{
reset=true;
}
return false;
}
#Override
public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
ArrayList<Prediction> predictions = gestureLib.recognize(gesture);
for (Prediction prediction : predictions) {
if (prediction.score > 1.0) {
Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT)
.show();
}
}
}
}

Delete your onTouch() method, or at least chain to the superclass instead of simply returning false, and see if that helps.

Related

Issue with getting GestureDetector to work with handleMessage

my app shows a bunch of bitmaps that animate one by one as it's stored in a Bitmap array and initially when app starts up curPosition is 0 to start animating obj at index 0. The handleMessage will animate each obj with a 1000ms delay between each obj when app starts up first time and so when app starts up first time handleMessage animates each obj normally.
The issue is once I double tap the restart button bitmap. I used the GestureDetector class and I have a Restart button constructed via a bitmap that when I listen for onDoubleTap and what should happen is the handleMessage will go thru each bitmap restarting animating them.
For some reason, when I double tap the Restart button bitmap, the handleMessage is running and i know this since I put in a logcat message and for that logcat message in update method I see it running thru each curPosition so I mean this line: Log.i ("cur pos. so far:", "" + curPosition );
but I don't visually see the animation running thru update method unless I interrupt app (i.e. close app OR minimize then resume app) and double tap the Restart button bitmap and the double tapping Restart button bitmap WORKS ONLY ONCE so I need to interrupt app to get it to work again.
public class MainActivity extends Activity implements
GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener {
private MySurfaceView mysurfaceView;
private Bitmap restart_buttonBitmap;
private GestureDetector mGestureDetector;
private MiniProj2Button restart;
private MiniProj2Button newLevel;
private final int SIZE = 5;
private final int DELAY = 1000;
private Bitmap[] myObjs = new Bitmap[ SIZE ];
//Screen size info
private int screenWidth;
private int screenHeight;
//The size in pixels of a place on the game board
private int blockSize;
private int numBlocksWide;
private int numBlocksHigh;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mySurfaceView = new MySurfaceView(this);
setContentView(mySurfaceView);
// Create a GestureDetector
mGestureDetector = new GestureDetector(this, this);
// Attach listeners that'll be called for double-tap and related gestures
mGestureDetector.setOnDoubleTapListener( this );
}//END METHOD: onCreate
#Override
protected void onStop() {
super.onStop();
Log.d("onStop", "Main Activity's onStop called");
gameView.surfaceDestroyed( mySurfaceView.getHolder() );
this.finish();
}
#Override
protected void onResume() {
super.onResume();
Log.d("onResume", "Main Activity's onResume called");
mySurfaceView = new MySurfaceView(this);
setContentView(mySurfaceView);
mySurfaceView.surfaceCreated( mySurfaceView.getHolder() );
}
#Override
protected void onPause() {
super.onPause();
Log.i("onPause", "Main Activity's onPause called");
mySurfaceView.surfaceDestroyed( mySurfaceView.getHolder() );
}
#Override
public boolean onDoubleTap(MotionEvent e) {
//reset animation if Restart button pressed!
if ( restart.isButtonTouched(e.getX(), e.getY(), blockSize,blockSize) ) {
curPosition = 0;
}
return true;
}
public void configureDisplay() {
//find out the width and height of the screen
Display display =
getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
//Determine the size of each block/place on the board
// blockSize = screenWidth/10;
blockSize = screenWidth/10;
//Determine how many blocks will fit into the
//height and width
// numBlocksWide = 10;
numBlocksWide = 10;
numBlocksHigh = ( ( screenHeight ) ) / blockSize;
}//END METHOD: configureDisplay
#Override
public boolean onTouchEvent(MotionEvent e) {
mGestureDetector.onTouchEvent(e);
return super.onTouchEvent(e);
}//END onTouchEvent
class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, Handler.Callback {
Canvas canvas = new Canvas();
SurfaceHolder surfaceHolder;//this lets us access the canvas but still need to use Canvas class
Handler myHandler;
Paint paint = new Paint ();
public MySurfaceView(Context context) {
super(context);
paint.setColor(Color.argb(255, 0, 0, 0));
path = new Path ();
myHandler = new Handler(this);
getHolder().addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
this.surfaceHolder = holder;
myHandler.sendEmptyMessage(0);
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
// What do I enter here???
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("Me", "surfaceDestroyed: bye!" );
myHandler.removeCallbacksAndMessages(null);
}
protected void drawIt ( ) {
if ( surfaceHolder.getSurface().isValid() ) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);//the background
//for each obj, draw it
surfaceHolder.unlockCanvasAndPost(canvas);
}//END IF BLOCK: For valid surfaceHolder
}//END METHOD: drawIt
public void update() {
Log.i ("cur pos. so far:", "" + curPosition );
if ( curPosition < SIZE ) {
myObjs [ curPosition ].animateMe ( );
curPosition++;
}
}//END METHOD: update
#Override
public boolean handleMessage(Message msg) {
if (curPosition < SIZE ) {
Log.i("Still objs 2 animate","Yes");
Log.i ("cur pos. so far:", "" + curPosition );
gameView.update();
gameView.drawIt();
myHandler.sendEmptyMessageDelayed(msg.what, DELAY);
}
else {
myHandler.sendEmptyMessageDelayed(msg.what, 10);
gameView.drawIt();
}
return true;
}//END METHOD: handleMessage
}//END INNER CLASS: MySurfaceView
}//END CLASS: MainActivity

[Android]onTouch in child View is not responding

I have been working on making Sudoku grid whose cell's value changes whenever I touch on a cell. So I have implemented this sudoku grid in a LinearLayout by Child View, and tried using OnTouch method, but it is not working. I tried using log method to check whether onTouch is actually called, but it seemes that this method is perfectly ignored. I have been searching for solutions on other question, but it seems none of those solutions helped. I feel kinda suck here, and any help would be greatly appreciated.
Here is my code:
SudokuActivity.java
package snacker.nonogramsolver;
import ...; /*many things are imported here*/
public class SudokuActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sudoku);
Button btn = (Button)findViewById(R.id.btn_clear);
Sudoku sdk = new Sudoku(this);
sdk.setOnTouchListener(sdk);
}
}
;
Sudoku.java
package snacker.nonogramsolver;
import ...;
public class Sudoku extends View implements View.OnTouchListener {
int mWidth = 9;
int mHeight = 9;
int mCellWidth, mCellHeight;
int mCellMargin;
int mEdgeThick;
int mStatus;
int mTextSize;
int mXNow = -1, mYNow = -1;
int[][] mBoard = new int[9][9];
Point mBoardPt;
Paint mTextPaint, mTileEdgePaint;
final static int VALID = 0;
public Sudoku(Context context){
super(context);
initializeBoard();
}
public Sudoku(Context context, AttributeSet attrs){
super(context, attrs);
initializeBoard();
}
#Override
protected void onDraw(Canvas canvas){
/* There are some codes here */
Log.d("LogTest","OnDraw Complete");
}
public void initializeBoard(){
for (int x=0; x< mWidth; x++){
for (int y=0; y< mHeight; y++){
mBoard[x][y] = 0;
}
}
invalidate();
}
public boolean onTouch(View v, MotionEvent event){
Log.d("LogTest","Touched?"); /* LOG NOT ACTIVE HERE */
if(event.getAction() == MotionEvent.ACTION_DOWN){
mXNow = getBoardX(event.getX());
Log.d("LogTest","" + mXNow); /* LOG NOT ACTIVE HERE */
mYNow = getBoardY(event.getY());
Log.d("LogTest","" + mYNow); /* LOG NOT ACTIVE HERE */
mBoard[mXNow][mYNow] = mBoard[mXNow][mYNow] + 1;
invalidate();
return true;
}
else return false;
}
int getBoardX(float scrx){
int x = (int)((scrx) / mCellWidth);
if (x < 0) x = 0;
if (x > 8) x= 8;
return x;
}
int getBoardY(float scry){
int y = (int)((scry) / mCellHeight);
if (y < 0) y = 0;
if (y > 8) y = 8;
return y;
}
}
Edit: added activity XML file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:id="#+id/activity_sudoku"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="snacker.nonogramsolver.SudokuActivity">
<snacker.nonogramsolver.Sudoku
android:id="#+id/SudokuGrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/btn_clear"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_weight="0.06"
android:text="Clear" />
</LinearLayout>
You cannot directly add touchListener by just creating object of
Sudoku class. You should add view in xml or programatically.
Your Activity
public class MyActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//initializing custom views
MyCustomView1 myCustomView1 = new MyCustomView1(parameterList);
MyCustomView2 myCustomView2 = new MyCustomView2(parameterList);
//adding both custom views to the main activity
mainView.addView(myCustomView1);
mainView.addView(myCustomView1);
//adding custom listener to the custom view 1
myCustomView1.setCustomEventListener(new OnCustomEventListener() {
#Override
public void onEvent() {
//firing an event of custom view 1
Toast.makeText(MainActivity.this, "Touched custom view 1",
Toast.LENGTH_SHORT).show();
}
});
//adding custom listener to the custom view 2
myCustomView2.setCustomEventListener(new OnCustomEventListener() {
#Override
public void onEvent() {
//firing an event of custom view 2
Toast.makeText(MainActivity.this, "Touched custom view 2",
Toast.LENGTH_SHORT).show();
}
});
}
}
Your CustomView 1
public class MyCustomView1 extends LinearLayout{
OnCustomEventListener myCustomEventListener;
public MyCustomView1(ParameterList){
super(ContextFromParameterList);
//Just adding something to the custom view 1 in order to distinguish it on the screen
TextView tv = new TextView(ContextFromParameterList);
tv.setText("Hello world from custom view 1");
addView(tv);
this.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//delegating one event to another (delegating touch event to custom event)
if (MyCustomView1.this.myCustomEventListener != null)
MyCustomView1.this.myCustomEventListener.onEvent();
return false;
}
}); }
public void setCustomEventListener(OnCustomEventListener
eventListener) {
//setting custom listener from activity
myCustomEventListener = eventListener; } }
Your CustomView2
public class MyCustomView2 extends LinearLayout {
OnCustomEventListener myCustomEventListener;
public MyCustomView2(ParameterList) {
super(ContextFromParameterList);
//Just adding something to the custom view 1 in order to distinguish it on the screen
TextView tv = new TextView(ContextFromParameterList);
tv.setText("Hello world from custom view 2");
addView(tv);
this.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
//delegating one event to another (delegating touch event to custom event)
if (MyCustomView2.this.myCustomEventListener != null)
MyCustomView2.this.myCustomEventListener.onEvent();
return false;
}
});
}
public void setCustomEventListener(OnCustomEventListener eventListener) {
//setting custom listener from activity
myCustomEventListener = eventListener;
}
}
Your listener interface:
public interface OnCustomEventListener{
//interface defines one method. Can be more and methods may have parameters
public void onEvent();
}

Android app does not get into onTouch method

I'm having troubles with the method onTouch(). The code I'm using to implement it is the following.
public class EjemploView extends View implements OnTouchListener {
...
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getActionMasked()==0) {
slider2.setCenX(slider2.getCenX() - 1);
}
return false;
}
}
The point is that I set a debugger stop inside onTouch method and even if I touch the screen it will never go inside it. What am I doing wrong?
Adding as an answer, simply so that it makes more sense.
You are implementing onTouchListener but you dont set it as your onTouchListener. Thus you are left with a fully functioning onTouchListener in your view that does not ever get called.
public EjemploView(Context context) {
super(context);
/** \/ Add this line right here \/ */
setOnTouchListener(this);
Resources res = context.getResources();
drawableFader = res.getDrawable(R.drawable.fader);
drawableSlider=res.getDrawable(R.drawable.slider);
fader1 = new Grafico(this, drawableFader);
fader2 = new Grafico(this, drawableFader);
slider1 = new Grafico(this, drawableSlider);
slider2 = new Grafico(this, drawableSlider);
fader1.setAlto(350);
fader1.setAncho(64);
fader2.setAlto(350);
fader2.setAncho(64);
fader2.setAngulo(90);
slider1.setAlto(90);
slider1.setAncho(55);
slider2.setAlto(90);
slider2.setAncho(55);
slider2.setAngulo(90);
}
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
setContentView(new EjemploView(this));
That's the place where I instantiate the view
public class EjemploView extends View implements OnTouchListener {
private Drawable drawableFader, drawableSlider;
private Grafico fader1, fader2, slider1, slider2;
public EjemploView(Context context) {
super(context);
Resources res = context.getResources();
drawableFader = res.getDrawable(R.drawable.fader);
drawableSlider=res.getDrawable(R.drawable.slider);
fader1 = new Grafico(this, drawableFader);
fader2 = new Grafico(this, drawableFader);
slider1 = new Grafico(this, drawableSlider);
slider2 = new Grafico(this, drawableSlider);
fader1.setAlto(350);
fader1.setAncho(64);
fader2.setAlto(350);
fader2.setAncho(64);
fader2.setAngulo(90);
slider1.setAlto(90);
slider1.setAncho(55);
slider2.setAlto(90);
slider2.setAncho(55);
slider2.setAngulo(90);
}
#Override
protected void onSizeChanged(int ancho, int alto, int ancho_anter, int alto_anter) {
super.onSizeChanged(ancho, alto, ancho_anter, alto_anter);
// Una vez que conocemos nuestro ancho y alto.
fader1.setCenX(ancho / 4 - 31);
fader1.setCenY(alto / 4 - 50);
slider1.setCenX(ancho / 4 - 28);
slider1.setCenY(alto / 4 - 50);
fader2.setCenX(ancho - 271);
fader2.setCenY(alto / 4 - 50);
slider2.setCenX(ancho - 277);
slider2.setCenY(alto / 4 - 50);
}
#Override
synchronized protected void onDraw(Canvas canvas) {
fader1.dibujaGrafico(canvas);
fader2.dibujaGrafico(canvas);
slider1.dibujaGrafico(canvas);
slider2.dibujaGrafico(canvas);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("TAG", "I've reached this point");
if(event.getActionMasked()==0) {
slider2.setCenX(slider2.getCenX() - 2);
}
return false;
}
}
And that's my whole code for the view. It is displaying it because I can see the drawables.
You are implementing a new interface, but you should use the already defined onTouchEvent(MotionEvent event). Just override it.
class CustomImageView extends ImageView {
...
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked();
Log.d(TAG, String.valueOf(action));
return false;
}
}

Android onClick only works once

So I'm realy confused
I am having a View(R.layout.main) which includes a custom view (canvas)
this View contains a button which is overlayed over the canvas
but when I click the button the OnClicklistener fires the event but after that button is doing nothing when clicked
Activity :
public class RunActivity extends Activity implements OnTouchListener, OnClickListener {
static int width;
static int height;
static boolean reset=false;
//draw d;
View d;
Button jump_button;
//jump
float last_touchpos=0;
static boolean jump=false;
private static Context mContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//d = new draw(this);
d = getLayoutInflater().inflate(R.layout.main, null);
d.setOnTouchListener(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
mContext = this;
//get screen size
WindowManager wm = (WindowManager) this.getContext().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
width = display.getWidth(); // deprecated
height = display.getHeight(); // deprecated
setContentView(d);
jump_button = (Button) findViewById(R.id.jump);
jump_button.setOnClickListener(this);
}
public static Context getContext(){
return mContext;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.d("touch","touched");
if (draw.end == true)
{
reset=true;
}
else
{
if(last_touchpos != 0)
{
if(last_touchpos < event.getY())
{
jump = true;
last_touchpos = 0;
}
}
else
{
last_touchpos = event.getY();
}
}
return false;
}
#Override
public void onClick(View arg0) {
jump = true;
}
}
Layout :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<run.alexander.fuchs.draw
android:id="#+id/canvasview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/jump"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Jump" />
</RelativeLayout>
static boolean jump=false;
remove static from this statement
boolean jump=false;
How can you sure your onClick is called once. Use a log print message within onClick method to make sure that it is called once. Your code is okay, and I hope your onClick works properly and check your rest of code.

Implementing OnTouchListener on LinearLayout - Android Development

public class UnitConverterActivity extends Activity implements OnTouchListener {
/** Called when the activity is first created. */
LinearLayout mLinearLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLinearLayout = new LinearLayout(this);
ImageView i = new ImageView(this);
i.setImageResource(R.drawable.mainmenu);
//i.setAdjustViewBounds(false);
i.setScaleType(ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mLinearLayout.addView(i);
setContentView(mLinearLayout);
//setContentView(R.layout.main);
}
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
return false;
}
}
I have used the above method to load an image for the main menu I am trying to create. The image has four areas and each will be used to call a particular function of the app. Now I am trying to implement touch interface on those areas. I know how to define the range of pixels for that purpose but I am at loss on how to implement OnTouchListner on the image. Please help me in this regard.
If your image was split into four rectangular quarters (say)
then in onCreate have:
i.setOnTouchListener(this);
and for your listener, something like this (illustrates the principle only):
#Override
public boolean onTouch(View v, MotionEvent mev) {
int width = v.getWidth();
int height = v.getHeight();
float x = mev.getX();
float y = mev.getY();
String msg;
if (x < width / 2) {
if (y < height / 2)
msg = "Top left quarter";
else
msg = "Bottom left quarter";
} else {
if (y < height / 2)
msg = "Top right quarter";
else
msg = "Bottom right quarter";
}
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
return false;
}
Just put this code in onCreate().
i.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//your code
}
}

Categories

Resources