Issue
How to make a button which when pressed would show a toast message asking the user to tap button again to confirm the action. Here is what I have so far,
Button myExitClose = alertLayout.findViewById(R.id.homeExitClose);
ImageView myExitDismiss = alertLayout.findViewById(R.id.homeExitDismiss);
final LinearLayout adContainer = alertLayout.findViewById(R.id.homeExitAdView);
myExitClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exitDialog.dismiss();
finish();
}
});
myExitDismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
exitDialog.dismiss();
}
});
alert.setView(alertLayout);
alert.setCancelable(false);
exitDialog = alert.create();
}
Solution
When the button is pressed, record the timestamp of the press. If the button is pressed again, compare the new timestamp to the old one, and perform the special action if the two presses happend close enough together.
private Long lastPressedTime = null;
button.setOnClickListener(v -> {
long currentTime = System.currentTimeMillis();
if (lastPressedTime == null || (currentTime - lastPressedTime) > 2000) {
Toast.makeText(v.getContext(), "Tap again to exit", Toast.LENGTH_SHORT).show();
lastPressedTime = currentTime;
} else {
finish();
}
});
You can change the 2000
to any number you want; 2000 millis is two seconds, but maybe you want a longer window.
Answered By - Ben P.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.