I'm trying to setup a way to only accept one gesture at a time then after that gesture is done do the next in line. So for example I want to start with a single tap then after you input the tap it would move on to the next one being a double tap. Here's the code I'm using:
import android.content.DialogInterface;
import android.support.v4.view.GestureDetectorCompat;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
public class secondscreen extends ActionBarActivity implements GestureDetector.OnGestureListener,
GestureDetector.OnDoubleTapListener{
private TextView mainMessage; //variable refers to strings.xml// private TextView InText;
private TextView startButton;
private GestureDetectorCompat gestureDetector; // Secondary Variable used for gestures
private DialogInterface.OnClickListener OnClickListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_secondscreen2);
mainMessage = (TextView) findViewById(R.id.mainMessage);
this.gestureDetector = new GestureDetectorCompat(this, this);
gestureDetector.setOnDoubleTapListener(this);
}
///////// GESTURE METHODS //////////
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
mainMessage.setText("single tap");
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
mainMessage.setText("double tap");
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
mainMessage.setText("double tapping event");
return false;
}
#Override
public boolean onDown(MotionEvent e) {
mainMessage.setText("down");
return false;
}
#Override
public void onShowPress(MotionEvent e) {
mainMessage.setText("showing the press");
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
mainMessage.setText("tap up");
return false;
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
mainMessage.setText("scrolling is fun");
return false;
}
#Override
public void onLongPress(MotionEvent e) {
mainMessage.setText("very long presses");
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
mainMessage.setText("flinging");
return false;
}
///////// GESTURE METHODS //////////
//this next block is needed to run gestures//
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
#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_secondscreen, 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);
}
}
I specifically want the gestures to not happen at the same time as it is set up now, the app will run the gestures and display a text but it does it all at the same time displaying the last one pressed - I want to know how to set it up on one screen so that it asks for a gesture and moves on to the next gesture after that one is pressed preferably waiting a second so it doesn't happen instantly. I'm pretty sure it has something to do with an if else statement but I have no idea how to word it.
One simple way I can think of is to just use an enum combined with if statements
enum ex.
private enum EVENT{
SINGLE_TAP,DOUBLE_TAP,EVENT_3,EVENT_4 ...;
}
private EVENT currentEvent=EVENT.SINGLE_TAP;
Event Handler
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (currentEvent==Event.SINGLE_TAP){
mainMessage.setText("single tap");
currentEvent=Event.DOUBLE_TAP;//set to next desired event
return true;
}
return false;
}
Do something similar in your other event handlers, on the last event i would make it loop back to the first
If you desire a delay between the events implement a stopwatch and check if your desired time has passed between events. Something like so.
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if(stopWatch.getTime > lastEventTime+delay){//pseudo code
if (currentEvent==Event.SINGLE_TAP){
mainMessage.setText("single tap");
currentEvent=Event.DOUBLE_TAP;//set to next desired event
return true;
}
}
return false;
}
Related
I wrote a simple code in MainActivity with its xml code previously which run successfully. Now, I want to make a fragment and run that MainActivity code in that fragment. I have tried everything, even by combining both codes etc. but all in vain. I'm attaching my MainActivity code below. This is the one I want to use in Fragment. I already know that fragment is like sub-activity of an activity and both have separate xmls too which I also know how to use. Just unable to use my MainActivity code from old app as FragmentActivity in a new app.
1) MainActivity Code which needs to act as a Fragment
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class MainActivity
extends AppCompatActivity
implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private TextView mytext;
private GestureDetector gestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //this is above two lines cox phly content set hoga tbi agy kam hna na
this.gestureDetector = new GestureDetector(this, this);
gestureDetector.setOnDoubleTapListener(this); }
//******************Upon clicking the button*************************
public void changetextshort(View v) {
mytext = (TextView) findViewById(R.id.mytext);
mytext.setText("Surpriseeee"); }
//******************initializing touch event*************************
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);}
//******************Implements Methods from alt+ins(0) for touch properties*************************
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
mytext.setText("I tapped Once");
return false;}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
mytext.setText("I tapped Twice");
return false;}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
mytext.setText("Double Tap Event Occurred");
return false;}
#Override
public boolean onDown(MotionEvent motionEvent) {
mytext.setText("Down goes");
return false;}
#Override
public void onShowPress(MotionEvent motionEvent) {
mytext.setText("I have pressed");}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
mytext.setText("Single Tap Up");
return false;}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I'm Scrolling");
return false;}
#Override
public void onLongPress(MotionEvent motionEvent) {
mytext.setText("I long pressed");}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I FLINNGED");
return false; }
}
2) Fragment Code (MainActivity is not having any code now except the basic code of Mainactivity like class name and OnCreate code - although I have added Mainactivity code in 3rd point too which needs to be actually almost like that when we make fragments in android app)
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class TopSectionFragment extends Fragment {
public class Top
extends AppCompatActivity
implements GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener{
private TextView mytext;
private GestureDetector gestureDetector;
//******************Override method oncreateview for fragment*************************
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment,container, false);
this.gestureDetector = new GestureDetector(this, this);
gestureDetector.setOnDoubleTapListener(this);
return view; //designing of top section fragment completed
}
//******************Upon clicking the button*************************
public void changetextshort(View v) {
mytext = (TextView) findViewById(R.id.mytext);
mytext.setText("Surpriseeee"); }
//******************initializing touch event*************************
#Override
public boolean onTouchEvent(MotionEvent event) {
this.gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);}
//******************Implements Methods from alt+ins(0) for touch properties*************************
#Override
public boolean onSingleTapConfirmed(MotionEvent motionEvent) {
mytext.setText("I tapped Once");
return false;}
#Override
public boolean onDoubleTap(MotionEvent motionEvent) {
mytext.setText("I tapped Twice");
return false;}
#Override
public boolean onDoubleTapEvent(MotionEvent motionEvent) {
mytext.setText("Double Tap Event Occurred");
return false;}
#Override
public boolean onDown(MotionEvent motionEvent) {
mytext.setText("Down goes");
return false;}
#Override
public void onShowPress(MotionEvent motionEvent) {
mytext.setText("I have pressed");}
#Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
mytext.setText("Single Tap Up");
return false;}
#Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I'm Scrolling");
return false;}
#Override
public void onLongPress(MotionEvent motionEvent) {
mytext.setText("I long pressed");}
#Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
mytext.setText("I FLINNGED");
return false; }
}
}
3) MainActivity code (which will incorporate Fragment sub-activity)
package com.ranatalha.userauthority;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity
extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); }
}
One of the main things to keep in mind when converting code from activities and fragments is that you may have to switch things that use context in them.
This line: this.gestureDetector = new GestureDetector(this, this); is likely one of the things that is giving you trouble.
This:
GestureDetector(Context context, GestureDetector.OnGestureListener listener)
is probably the constructor you are trying to use.
The parameters that are context, will need to be changed from this in an activity to getContext() (or to something that extends Context) in a fragment.
For creating the fragment in the first place:
https://developer.android.com/guide/components/fragments.html
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
The container mentioned in the code sample is normally something like a FrameLayout.
It is not clear what you mean by "make a fragment and run that MainActivity code in that fragment"...
If you want to start an activity and make it overlay the Fragment you can try the code from MCeley in Start an activity from a fragment
> Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
> startActivity(intent);
I am very new to programming and I have a problem with a game which I am trying to make.
Almost every time when I exit the game it was crashing.
After adding: if (canvas != null) beforew canvas.drawColor(Color.CYAN); it does not crash on exit anymore but when I return to the game.
Here is the code: (its not my actual game... there is nothing in OnDraw exept canvas.drawColor(Color.CYAN); that keeps it simple)
GameView.java:
package com.example.test.threadtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread theGameLoopThread;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onDraw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(Color.CYAN);
}
}
GameLoopThread.java:
package com.example.test.threadtest;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView theView;
private boolean isRunning = false;
public GameLoopThread(GameView theView) {
this.theView = theView;
}
public void setRunning(boolean run) {
isRunning = run;
}
#SuppressLint("WrongCall") #Override
public void run() {
long TPS = 1000 / FPS;
long startTime, sleepTime;
while (isRunning) {
Canvas theCanvas = null;
startTime = System.currentTimeMillis();
try {
theCanvas = theView.getHolder().lockCanvas();
synchronized (theView.getHolder()) {
theView.onDraw(theCanvas);
}
} finally {
if (theCanvas != null) {
theView.getHolder().unlockCanvasAndPost(theCanvas);
}
}
sleepTime = TPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
}
MainAcitvity.java:
package com.example.test.threadtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#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);
}
}
I am trying to accept BrainTree on my app. I don't understand the Async HTTP Client part.
Where do I place this in my app? Currently, I have it in the MainActivity and it is giving me errors for 'get', 'TextHttpResponseHandler' as well as 'clientToken'.
Any ideas?
package com.example.android.payments;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.loopj.android.http.*;
import com.braintreepayments.api.dropin.BraintreePaymentActivity;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://your-server/client_token", new TextHttpResponseHandler() {
#Override
public void onSuccess(String clientToken) {
this.clientToken = clientToken;
}
});
public void onBraintreeSubmit(View v) {
Intent intent = new Intent(context, BraintreePaymentActivity.class);
intent.putExtra(BraintreePaymentActivity.EXTRA_CLIENT_TOKEN, clientToken);
// REQUEST_CODE is arbitrary and is only used within this activity.
startActivityForResult(intent, REQUEST_CODE);
}
#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);
}
}
Your call to client.get() is not in a method body, so your code is not syntactically valid. Try putting it in a method (or constructor or initializer block - but it's a bad idea to do work in either of those places).
For example, you could put that statement in a new method called fetchClientToken():
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) { ... }
AsyncHttpClient client = new AsyncHttpClient();
public void fetchClientToken() {
client.get("https://your-server/client_token", new TextHttpResponseHandler() {
#Override
public void onSuccess(String clientToken) {
this.clientToken = clientToken;
}
});
}
public void onBraintreeSubmit(View v) { ... }
#Override public boolean onCreateOptionsMenu(Menu menu) { ... }
#Override public boolean onOptionsItemSelected(MenuItem item) { ... }
}
You then need to invoke fetchClientToken somehow, just like you would with any other method.
I am trying to make a read aloud menu option here. This is the code I have written. But it doesn't really read aloud the text on the card. The doc says that if there is any text set on the card it will read aloud. My card has some text on it :
newcard.setText("text");
My MenuActivity which is called looks like this.
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MenuActivity extends Activity {
public Object json(int menuid)
{
JSONObject obj = new JSONObject();
try {
System.out.println("goes into try of json");
obj.put("text", "Hello World");
obj.put("menuItems", new JSONObject().put("action", "READ_ALOUD"));
System.out.println(obj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return obj;
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
openOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.second, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection.
switch (item.getItemId()) {
case R.id.read_aloud_menu_item:
System.out.println("goes itno read aloud case");
json(item.getItemId());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onOptionsMenuClosed(Menu menu) {
// Nothing else to do, closing the activity.
finish();
}
}
I am really not sure wheteher I can pass the JSON like this. If not like this, how else can I do this?
I am not sure where you read that Glass would automatically read this aloud...
You should use TextToSpeech as in the gdk-compass-sample provided by Google.
Create a field in your Activity
public class MenuActivity extends Activity {
private TextToSpeech mSpeech;
...
}
Initialise in OnCreate
#Override
public void onCreate() {
super.onCreate();
...
mSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// Do nothing.
}
});
}
Call the speak function in your onOptionsItemSelected event
mSpeech.speak(json(item.getItemId()).text, TextToSpeech.QUEUE_FLUSH, null);
Close everything down in the onDestroy event
#Override
public void onDestroy() {
mSpeech.shutdown();
mSpeech = null;
super.onDestroy();
}
thank you so much for reading. I have a textView that you can pinch zoom, and when I add "textview.setMovementMethod(new ScrollingMovementMethod());" to my code I can also scroll the zoomed textview which is exactly what I need. The problem is as soon as the text is zoomed, only the scrolling works but the pinch zoom doesnt work anymore, (unless I place one of my fingers outside the textview and the other inside). Any help will be really appreciated. I got the code from here: Pinch Zooming TextView
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView scaleGesture;
ScaleGestureDetector scaleGestureDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scaleGesture = (TextView)findViewById(R.id.article);
scaleGesture.setText("this is some text");
scaleGestureDetector = new ScaleGestureDetector(this, new simpleOnScaleGestureListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
scaleGestureDetector.onTouchEvent(event);
return true;
}
public class simpleOnScaleGestureListener extends
SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
float size = scaleGesture.getTextSize();
Log.d("TextSizeStart", String.valueOf(size));
float factor = detector.getScaleFactor();
Log.d("Factor", String.valueOf(factor));
float product = size*factor;
Log.d("TextSize", String.valueOf(product));
scaleGesture.setTextSize(TypedValue.COMPLEX_UNIT_PX, product);
size = scaleGesture.getTextSize();
Log.d("TextSizeEnd", String.valueOf(size));
return true;
}
}
}`
I just resolve this problem (with the same example) only add one "if" in my code:
#Override
public boolean onTouchEvent(MotionEvent event) {
// get how many fingers is in touch (in that case, if are more
// than 1, the user don't want do the scroll
if (event.getPointerCount() > 1) {
scaleGestureDetector.onTouchEvent(event);
return true;
}
return false;
}