Android Error: Undefined Method - android

I've got a Fragment (ActionBarSherlock Tabs), and I want to run a Chronometer in Background:
public class BFragment extends SherlockFragment {
private Button start;
private View v;
private Chronometer chrono;
private Button pause;
private Button reset;
private long lastPause;
private Button resume;
private boolean isChronometerRunning = false;
private boolean richtig = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.activity_bfragment, container, false);
start = (Button) v.findViewById(R.id.start);
chrono = (Chronometer) v.findViewById(R.id.chronometer1);
pause = (Button) v.findViewById(R.id.pause);
reset = (Button) v.findViewById(R.id.reset);
resume = (Button) v.findViewById(R.id.resume);
new ChronoBackground().execute();
return v;
}
void StartTimer() {
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
isChronometerRunning = true;
System.out.println(SystemClock.elapsedRealtime());
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
chrono.stop();
isChronometerRunning = false;
richtig = true;
}
});
resume.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (isChronometerRunning == false && richtig) {
chrono.setBase(chrono.getBase() + SystemClock.elapsedRealtime() - lastPause);
chrono.start();
richtig = false;
} else {
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
System.out.println(chrono.getBase());
}
});
}
}
And here is my ChronBackground class/code:
public class ChronoBackground extends AsyncTask<Void, Void, Void> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
StartTimer();
return null;
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
#Override
protected void onPostExecute(Void result) {
return ;
}
#Override
protected void onPreExecute() {
return ;
}
}
Now there's an error, and I'm not really sure if my chrono is working this way... The error is at ChronoBackground: StartTimer() not defined.

The mistake is perhaps in the fact, that ChronoBackground is not an innerclass of BFragment and doesn't see the method?

Related

How can I make my ImageButton behave differently depending on ToggleButton status?

I am trying to add a toggle button, so that my image button switches the direction that it translates based on the status of the toggle button. However, I am running into problems when trying to add it to the media player, and when using the if statement.
public class MainActivity extends AppCompatActivity {
TextToSpeech tts1;
ToggleButton toggleButton;
public void changeTranslation(View view){
boolean on = ((ToggleButton)view).isChecked();
if(on){
toggleButton.setText("Speech-to-Farts");
Toast.makeText(getApplicationContext(),"Translating speech to farts.",Toast.LENGTH_SHORT);
} else{
toggleButton.setText("Farts-to-Speech");
Toast.makeText(getApplicationContext(),"Translating farts to speech.",Toast.LENGTH_SHORT);
}
}
private static final String TAG = "MainActivity";
private MediaPlayer mMediaPlayer;
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mediaPlayer){
releaseMediaPlayer();
}
};
private void releaseMediaPlayer(){
if(mMediaPlayer != null){
mMediaPlayer.release();
mMediaPlayer=null;
}
}
TextView tv1;
ImageButton b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(textView);
b1 = (ImageButton) findViewById(R.id.recordButton);
final ToggleButton toggleButton = (ToggleButton) findViewById(R.id.toggle_button);
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (toggleButton.isChecked()) {
toggleButton.setText("Farts-to-Speech");
} else {
toggleButton.setText("Speech-to-Farts");
}
}
});
tts1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
tts1.setLanguage(Locale.US);
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
int[] fartLibrary={};
String[] speechLibrary={};
if(toggleButton==true) {
releaseMediaPlayer();
String randomTranslation = (speechLibrary[new Random().nextInt(speechLibrary.length)]);
tts1.speak(randomTranslation, TextToSpeech.QUEUE_FLUSH, null);
} else {
releaseMediaPlayer();
mMediaPlayer=MediaPlayer.create(this,fartLibrary);
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
}
}
This is my Translations.java. I'm not sure if this is necessary anymore though
public class Translations{
private String mSpeechTranslation;
private int mFartTranslation;
public Translations(String speechTranslation, int fartTranslation){
mFartTranslation = fartTranslation;
mSpeechTranslation = speechTranslation;
}
public String getmSpeechTranslation(){ return mSpeechTranslation;}
public int getmFartTranslation(){ return mFartTranslation;}
}

Restarting a CountDownTimer in a Dialog window after an OnTouchEvent in a fragment

I have a CountDownTimer that dismisses a dialog popup window. I would like for this timer to restart if the user touches the screen. Here is what I have so far,
public class dataCapture extends Fragment implements OnClickListener {
...
MotionEvent event;
View.OnTouchListener touchListener;
#Override
public void onCreate(Bundle savedDataEntryInstanceState) {
super.onCreate(savedDataEntryInstanceState);
setRetainInstance(true);
}
...
#Override
public View onCreateView
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnHelpFilexml:
openHelpDialog();
break;
...
}
private void openHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody = (TextView) helpDialog.findViewById(R.id.tvHelpDialogBody);
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Here we go...\n" +
...
"This is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
CountDownTimer countDownTimer = new CountDownTimer(30000, 1000) {
// new countDownTimer(30000, 1000) {//makes popup go away after 30 secs
#Override
public void onTick(long millisUntilFinished) {//Do something every second...
}
#Override
public void onFinish() {//action at end of specified time
helpDialog.dismiss();
}
}.start();
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
countDownTimer.cancel();
countDownTimer.start();
}
return super.onTouchEvent(event);
}
helpDialog.show();
}
}
Any suggestions regarding how best to implement this function would be highly appreciated. Copious TIA.
UPDATE Got it. Solution below. Thanks.
public class dataCapture extends Fragment implements OnClickListener {
...
private static final int COUNTDOWN_TIME_MS = 30000;
Handler handlerHelpDialogTimer;
Runnable runnableHelpDialogDismissCountdown;
Dialog helpDialog;
private Dialog getHelpDialog() {
Button btnCloseWindow;
final Dialog helpDialog;
TextView tvHelpDialogTitle, tvHelpDialogBody;
helpDialog = new Dialog(getActivity(), android.R.style.Theme_Translucent);
helpDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
helpDialog.setCancelable(true);
helpDialog.setContentView(R.layout.help_dialog);
tvHelpDialogTitle = (TextView) helpDialog.findViewById(R.id.tvHelpDialogTitle);
tvHelpDialogTitle.setText("DataCapture Help");
tvHelpDialogBody.setText("Start of help text\n" +
"This is help text\n" +
"\n" +
"Wheee, here we go\n" +
...
"this is the end.");
btnCloseWindow = (Button) helpDialog.findViewById(R.id.btnCloseWindow);
btnCloseWindow.setText("Close");
btnCloseWindow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpDialog.dismiss();
}
});
tvHelpDialogBody.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View tvHelpDialogBody, MotionEvent event) {
cancelCountdown();
startCountdown();
return false;
}
});
helpDialog.show();
return (helpDialog);
}
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountdown();
}
synchronized private void startCountdown() {
handlerHelpDialogTimer.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handlerHelpDialogTimer.removeCallbacks(runnableHelpDialogDismissCountdown);
runnableHelpDialogDismissCountdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override
public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
runnableHelpDialogDismissCountdown = task;
return task;
}
Ditch the countdown timer. Instead use a handler, for example:
public class AwesomeActivity extends Activity {
private static final int COUNTDOWN_TIME_MS = 300000;
Handler handler;
Runnable countDown;
Dialog helpDialog;
#Override public void onCreate(Bundle b) {
super.onCreate(b);
handler = new Handler();
}
/* call cancelCountdown() in onPause* */
private Dialog getHelpDialog() { return /* fill in the details */ }
private void showHelpDialog() {
helpDialog = getHelpDialog();
helpDialog.show();
startCountDown();
}
synchronized private void startCountDown() {
handler.postDelayed(getCountdownTask(), COUNTDOWN_TIME_MS);
}
synchronized private void cancelCountdown() {
handler.removeCallbacks(countdown);
countdown = null;
}
private Runnable getCountdownTask() {
Runnable task = new Runnable() {
#Override public void run() {
if (helpDialog != null) helpDialog.dismiss();
}
};
countDown = task;
return task;
}
}
Now in onTouch(MotionEvent e) you can cancel and start the countdown.
I'll leave it to you to figure out how to handle onPause and onResume :)
Furthermore, if you really wanted to, you could override a Dialog and put the Handler timer countdown logic inside that class, overriding show() to start the countdown and then add a method such as, restartTimer() you can call after a TOUCH_DOWN. If you do, you can then also override onSaveInstanceState and onRestoreInstanceState in the Dialog subclass, to cancel the callback, stash the time remaining, then pull out the time remaining and re-postdelay the countdown runnable with the remaining time.

AsyncTask Example w/ Chronometer

I've got a Chronometer, but when I change my View (with ActionBar) it stops.
I don't really understand how to use AsyncTask, and I didn't find a Tutorial.
Is there something easy to solve my problem? I would really like an example with Chronometer...
Thanks very much!
Code so far:
public class BFragment extends SherlockFragment {
private Button start;
private View v;
private Chronometer chrono;
private Button pause;
private Button reset;
private long lastPause;
private Button resume;
private Boolean richtig;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.activity_bfragment, container, false);
start = (Button) v.findViewById(R.id.start);
chrono = (Chronometer) v.findViewById(R.id.chronometer1);
pause = (Button) v.findViewById(R.id.pause);
reset = (Button) v.findViewById(R.id.reset);
resume = (Button) v.findViewById(R.id.resume);
richtig = true;
new chronom().execute();
return v;
}
private class chronom extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
System.out.println(SystemClock.elapsedRealtime());
richtig = false;
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
lastPause = SystemClock.elapsedRealtime();
chrono.stop();
richtig = true;
}
});
resume.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (richtig) {
chrono.setBase(chrono.getBase() + SystemClock.elapsedRealtime() - lastPause);
chrono.start();
} else {
}
}
});
reset.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
chrono.setBase(SystemClock.elapsedRealtime());
System.out.println(chrono.getBase());
richtig = false;
}
});
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
}
}
I just copied the code... (Chrono works, but not in Background)

How should I reuse the AnymoteClient service, so that I do not have to re-pair with google tv when I launch a new activity?

I am doing some investigations with the GoogleTV and a Android tablet. I have managed to make an android application that can send control messages to the google tv from the main Activity, what I am trying to do is launch a new activity from the main Activity and continue using the AnymoteClientService Service with the new activity. In my main activity I get an anymoteSender handle which I use to send KeyEvent messages to the google tv, how do I transfer this to the new activity (SlidepuzzleActivity)? I could instantiate it all again, but that would mean having to go through the whole pairing process again.
From the code below you will see that I have an anymoteSender in my SlidepuzzleActivity class, this will throw an error, but illustrates where I need to reuse that variable.
Code:
MainActivity.java:
package uk.co.myapp.gtvremote;
//imports removed for paste
public class MainActivity extends Activity implements ClientListener{
private AnymoteSender anymoteSender;
private TextView statusText;
protected AnymoteClientService mAnymoteClientService;
private static String statusPrefix = "Status: ";
private Context mContext;
private ProgressBar progressBar;
private Handler handler;
private TouchHandler touchPadHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progressBar = (ProgressBar) findViewById(R.id.a_progressbar);
progressBar.setVisibility(View.VISIBLE);
mContext = this;
ImageButton upArrowButton = (ImageButton) findViewById(R.id.upArrow);
ImageButton leftArrowButton = (ImageButton) findViewById(R.id.leftArrow);
ImageButton centreButton = (ImageButton) findViewById(R.id.centreButton);
ImageButton rightArrowButton = (ImageButton) findViewById(R.id.rightArrow);
ImageButton downArrowButton = (ImageButton) findViewById(R.id.downArrow);
ImageButton backButton = (ImageButton) findViewById(R.id.backButton);
ImageButton homeButton = (ImageButton) findViewById(R.id.homeButton);
Button testButton = (Button) findViewById(R.id.testButton);
upArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_UP);
}
});
leftArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_LEFT);
}
});
centreButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_CENTER);
}
});
rightArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_RIGHT);
}
});
downArrowButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_DPAD_DOWN);
}
});
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_BACK);
}
});
homeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendKeyEvent(KeyEvent.KEYCODE_HOME);
}
});
testButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(MainActivity.this, SlidepuzzleActivity.class);
MainActivity.this.startActivity(myIntent);
}
});
handler = new Handler();
// Bind to the AnymoteClientService
Intent intent = new Intent(mContext, AnymoteClientService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
statusText = (TextView) findViewById(R.id.statusText);
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
/*
* ServiceConnection listener methods.
*/
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAnymoteClientService = ((AnymoteClientService.AnymoteClientServiceBinder) service)
.getService();
mAnymoteClientService.attachClientListener(MainActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mAnymoteClientService.detachClientListener(MainActivity.this);
mAnymoteClientService = null;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onConnected(AnymoteSender anymoteSender) {
if (anymoteSender != null) {
// Send events to Google TV using anymoteSender.
// save handle to the anymoteSender instance.
this.anymoteSender = anymoteSender;
attachTouchListnertoTouchPad();
} else {
statusText.setText(statusPrefix + "Connection attempt failed, cant find send handler");
//attempt to connect again?
//attemptToConnect();
}
// Hide the progressBar once connection to Google TV is established. Make the text display appropriately
handler.post(new Runnable() {
public void run() {
progressBar.setVisibility(View.INVISIBLE);
statusText.setText(statusPrefix + "Connected to GoogleTV");
}
});
}
#Override
public void onDisconnected() {
// show message to tell the user about disconnection.
statusText.setText(statusPrefix + "Disconnected");
// Try to connect again if needed. This may be need to be done via button
attemptToConnect();
this.anymoteSender = null;
}
#Override
public void onConnectionError() {
// show message to tell the user about disconnection.
statusText.setText(statusPrefix + "Connection error encountered");
// Try to connect again if needed.
attemptToConnect();
this.anymoteSender = null;
}
#Override
protected void onDestroy() {
if (mAnymoteClientService != null) {
mAnymoteClientService.detachClientListener(this);
}
unbindService(mConnection);
super.onDestroy();
}
private void attachTouchListnertoTouchPad()
{
// Attach touch handler to the touchpad view
touchPadHandler = new TouchHandler(
findViewById(R.id.touchPad), Mode.POINTER_MULTITOUCH, anymoteSender);
}
public void attemptToConnect()
{
//stub to invoke connection attempt
}
private void sendKeyEvent(final int keyEvent) {
// create new Thread to avoid network operations on UI Thread
if (anymoteSender == null) {
Toast.makeText(MainActivity.this, "Waiting for connection",
Toast.LENGTH_LONG).show();
return;
}
anymoteSender.sendKeyPress(keyEvent);
}
}
SlidepuzzleActivity.java:
package uk.co.myapp.gtvremote;
//imports removed for paste
public class SlidepuzzleActivity extends Activity implements ClientListener{
private AnymoteClientService mAnymoteClientService;
private Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.slidepuzzle);
mContext = this;
ImageButton piece1x1 = (ImageButton) findViewById(R.id.piece1x1);
ImageButton piece1x2 = (ImageButton) findViewById(R.id.piece1x2);
ImageButton piece1x3 = (ImageButton) findViewById(R.id.piece1x3);
ImageButton piece2x1 = (ImageButton) findViewById(R.id.piece2x1);
ImageButton piece2x2 = (ImageButton) findViewById(R.id.piece2x2);
ImageButton piece2x3 = (ImageButton) findViewById(R.id.piece2x3);
ImageButton piece3x1 = (ImageButton) findViewById(R.id.piece3x1);
ImageButton piece3x2 = (ImageButton) findViewById(R.id.piece3x2);
ImageButton piece3x3 = (ImageButton) findViewById(R.id.piece3x3);
Intent intent = new Intent(mContext, AnymoteClientService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
piece1x1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private ServiceConnection mConnection = new ServiceConnection() {
/*
* ServiceConnection listener methods.
*/
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAnymoteClientService = ((AnymoteClientService.AnymoteClientServiceBinder) service)
.getService();
mAnymoteClientService.attachClientListener(SlidepuzzleActivity.this);
}
#Override
public void onServiceDisconnected(ComponentName name) {
mAnymoteClientService.detachClientListener(SlidepuzzleActivity.this);
mAnymoteClientService = null;
}
};
private void sendKeyEvent(final int keyEvent) {
// create new Thread to avoid network operations on UI Thread
if (anymoteSender == null) {
Toast.makeText(SlidepuzzleActivity.this, "Waiting for connection",
Toast.LENGTH_LONG).show();
return;
}
anymoteSender.sendKeyPress(keyEvent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.slidepuzzle, menu);
return true;
}
#Override
public void onConnected(AnymoteSender anymoteSender) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onConnectionError() {
// TODO Auto-generated method stub
}
#Override
protected void onDestroy() {
if (mAnymoteClientService != null) {
mAnymoteClientService.detachClientListener(this);
}
unbindService(mConnection);
super.onDestroy();
}
}
Just published an update to AnymoteLibrary for this.
In your MainActivity call both bindService() (already) and startService() for AnymoteClientService. The reason behind calling startService() is to keep the service and its anymoteSender instance around so that other Activitys in the same app can use it.
In the second Activity, implement ClientListener ( if you want to get onDisconnected() callback) and bind to the service and attachClientListener(). To get the AnymoteSender instance, call AnymoteClientService.getAnymoteSender(). Note that it can return null if the connection to Google TV is lost.
When all Activitys are done using AnymoteSender, remember to call stopService() for AnymoteClientService.

Implement double click for button in Android

How can I implement double click for a button in Android?
Should I use OnDoubleTapListener?
int i = 0;
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
i++;
Handler handler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
i = 0;
}
};
if (i == 1) {
//Single click
handler.postDelayed(r, 250);
} else if (i == 2) {
//Double click
i = 0;
ShowDailog();
}
}
});
private long lastTouchTime = 0;
private long currentTouchTime = 0;
..
#Override
public void onClick(View view) {
lastTouchTime = currentTouchTime;
currentTouchTime = System.currentTimeMillis();
if (currentTouchTime - lastTouchTime < 250) {
Log.d("Duble","Click");
lastTouchTime = 0;
currentTouchTime = 0;
}
}
This is probably a good place to start:
Android: How to detect double-tap?
I recommend switching to a more native way like long press (answer to linked question) or something more creative (using multi-touch), unless you are bent on the Windows default double-click way of doing things?
You may have a valid reason though - double clicking is after all faster than long press.
I wrote this for popping up a Toast message on a double click in a mapping application:
private long lastTouchTime = -1;
#Override
public boolean onTouchEvent(MotionEvent e, MapView mapView) {
GeoPoint p = null;
if (e.getAction() == MotionEvent.ACTION_DOWN) {
long thisTime = System.currentTimeMillis();
if (thisTime - lastTouchTime < 250) {
// Double click
p = mapView.getProjection().fromPixels((int) e.getX(), (int) e.getY());
lastTouchTime = -1;
} else {
// too slow
lastTouchTime = thisTime;
}
}
if (p != null) {
showClickedLocation(p);// Raise a Toast
}
return false;
}
This is a good site for performing double click...
I used it and worked.
http://mobile.tutsplus.com/tutorials/android/android-gesture/
I used it and worked:
public class DoubleClickTest extends Activity {
String TAG = "DoubleOrSingleClickTest";
private boolean waitDouble = true;
private static final int DOUBLE_CLICK_TIME = 350; // double click timer
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.double_click_test);
Button button = (Button) findViewById(R.id.buttonDoubleOrSingleClicked);
button.setOnClickListener(listenerDoubleOrSingle);
}
View.OnClickListener listenerDoubleOrSingle = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (waitDouble == true) {
waitDouble = false;
Thread thread = new Thread() {
#Override
public void run() {
try {
sleep(DOUBLE_CLICK_TIME);
if (waitDouble == false) {
waitDouble = true;
singleClick();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
} else {
waitDouble = true;
doubleClick();
}
}
};
// single event
private void singleClick() {
Log.i(TAG, "singleClick");
}
// double event
private void doubleClick() {
Log.i(TAG, "doubleClick");
}
}
It comes from "https://elingwange.iteye.com/blog/1613177"
Create your own DoubleTapListener
You can create a DoubleTapListener by inheriting View.OnClickListener and adding a Callback of your listener.
MyDoubleClickListener.class
public class MyDoubleClickListener implements View.OnClickListener{
private boolean isRunning= false;
private int resetInTime =500;
private int counter=0;
private DoubleClickCallback listener;
public DoubleTapListener(Context context)
{
listener = (DoubleClickCallback)context;
}
#Override
public void onClick(View v) {
if(isRunning)
{
if(counter==1) //<-- makes sure that the callback is triggered on double click
listener.onDoubleClick(v);
}
counter++;
if(!isRunning)
{
isRunning=true;
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(resetInTime);
isRunning = false;
counter=0;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
DoubleClickCallback.class
public interface DoubleClickCallback {
public void onDoubleClick(View v);
}
And you are done. You can use this Listener in any Activity.
How do I use this DoubleClickListener in my Activity?
Implement Callback in your activity and override the method.
public class MainActivity extends AppCompatActivity implements MyDoubleClickListener{
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new DoubleTapListener(this)); //<-- Set listener
}
#Override
public void onDoubleClick(View v) {
// Toast to show double click
}
}
Important point is using this concept you can create any kind of listener (Triple-click listener)
Relevant Links:
See the full working code HERE

Categories

Resources