Reputation:
I would like to show a dialog (secret menu) when a user taps 5 times anywhere in the activity. Is this somehow possible? I wasn't able to achieve this and also haven't found anything in the documentation.
Upvotes: 0
Views: 337
Reputation: 5069
This is pretty easy. The code will go like this :
public class MainActivity extends Activity {
private int count = 0;
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
if (eventaction == MotionEvent.ACTION_UP) {
count++;
}
else{
break;
}
if (count==5) {
//do whatever you need
Toast.makeText(getActivity(), "You tapped 5 times on screen",
Toast.LENGTH_LONG).show();
}
return true;
}
return false;
}
Upvotes: 0
Reputation: 6813
For your information
Yes you can override onTouchEvent(MotionEvent event)
But
User get the secret menu whenever he complete the 5 touches.
But for a real Secret Menu,When ever the user touches 5 times Quickly the dialogue shows up.
For that
public class MainActivity extends Activity {
private final int count = 0;
Handler handler;
Runnable runnable;
@Override
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
if (eventaction == MotionEvent.ACTION_UP) {
count++;
if (count > 0) {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
count = 0;
}
};
handler.postDelayed(runnable, 1000); // clear counter if user does not touch for one sec
}
if (count == 5) {
//do whatever
}
return true;
}
return false;
}
}
If the user does not touch for a moment make the counter to 0.
Be careful to import right handler
import android.os.Handler;
Upvotes: 0
Reputation: 34180
First Intialize global variable mCounter which keep track how many time you click on activity.
int mCounter = 0;
you can override onTouchEvent method like below inside activity
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// increase counter here
counter = counter + 1;
if(counter == 5) {
// show dialog here
}
break;
}
return true;
}
}
Hope these help you.
Upvotes: 0
Reputation: 23881
try this code: overwrite the onTouchEvent(MotionEvent event)
method in your activity and count number of taps..
public class MainActivity extends Activity {
private int count = 0;
//detect any touch event in the screen
@Override
public boolean onTouchEvent(MotionEvent event) {
int eventaction = event.getAction();
if (eventaction == MotionEvent.ACTION_UP) {
//get system current milliseconds
long time= System.currentTimeMillis();
++count;
if (count==5) {
//show Dialog
new AlertDialog.Builder(MainActivity.this)
.setTitle("Your Alert")
.setMessage("Your Message")
.setCancelable(false)
.setPositiveButton("ok", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Whatever...
}
}).show();
}
return true;
}
return false;
}
}
Upvotes: 1