How to disable button for 1 sec after clicked in Android? - android

I am using following code for using a button. I works.(sendBtn is a button in a fragment)
sendText = view.findViewById(R.id.send_text);
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
Now i want to disable the button for 1 sec after a click
I found following solution but above code works "without onClick(View v)"method and without implementing View.OnClickListener in class. How to provide delay in such case..How code is working without onClick method.
#Override
public void onClick(View v) {
((Button) findViewById(R.id.click)).setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
((Button) findViewById(R.id.click))
.setEnabled(true);
}
}, 1000);
}
});

Use this method when you want to interrupt user clicks:
private static long mLastClickTime = 0L;
public static boolean isOpenRecently() {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return true;
}
mLastClickTime = SystemClock.elapsedRealtime();
return false;
}
Usage:
if (v.getId() == R.id.sendBtn) {
if (isOpenRecently()) return;
// Your logic
}

Basically you are using lambda in your code, where v->{} represents the onCLick(View v) function.
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
You can do the following to disable the button for 1 second
void doOnSendButtonClick(View v){
//Send the message (your logic here)
send(sendText.getText().toString());
//Disable button
sendBtn.setEnabled(false);
//enable button after 1000 millisecond
new Handler(Looper.getMainLooper()).postDelayed(() -> {
sendBtn.setEnabled(true);
}, 1000);
}
And call this method when user clicks on the button
sendButton.setOnClickListener(view -> doOnSendButtonClick(view));

You could use a CountDownTimer.
CountDownTimewr timer = new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
// enable button
((Button) findViewById(R.id.click)).setEnabled(true);
}
}
#Override
public void onClick(View v) {
// disable btn and start timer of one second in millis
((Button) findViewById(R.id.click)).setEnabled(false);
timer.start();
}
});

Please try this way
Handler(Looper.getmainLooper()) and remove callback after you done your task inside runnable thread...also try to put this logic in any method outside in this class and call from setonclicklistener
Try the Timer.shedule with timertask
you can use runOnUIThread method inside where you can update UI.
you can also try to check the time difference of click and enable again in looping like while.

Related

How to pause the countdown timer if activity dialog appeared

How can I pause the countdownTimer if a dialog need to appear first. What can I do so that the timer will not start until I click the ok button.
countDownTimer = new CountDownTimer(320000, 1200) {
#Override
public void onTick(long l) {
timeText.setText(String.valueOf(timeValue));
timeValue = timeValue - 1;
if (timeValue == -1){
FLAG = 3;
playAudio.setAudioforEvent(FLAG);
timerDialog.timerDialog();
countDownTimer.cancel();
dbHandler.addScore2(tag,Integer.parseInt(txtCorrect.getText().toString()));
}
}
#Override
public void onFinish() {
// timerDialog.timerDialog();
}
}.start();
This is the dialog that will appear first.
public void fillDialog(){
fillDialog = new Dialog(mnContext);
fillDialog.setContentView(R.layout.activity_instruction_fill);
final Button btdialog = (Button) fillDialog.findViewById(R.id.ok_btn_fill);
btdialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fillDialog.dismiss();
}
});
You can use the countdownTimer.cancel() method to pause the countdown timer. When the dialog appears, call this method to pause the timer. When the user clicks the "OK" button on the dialog, you can then call the countdownTimer.start() method to resume the timer from where it left off.
Alternatively, you can also use countdownTimer.pause() and countdownTimer.resume() to pause and resume the timer.
It would be good to keep in mind that countdownTimer is a android class and you need to call the above methods from your activity class

How to disable a button for multiple click?

I have a button that when click shows a dialog. But when you click the button quickly in multiple times, it will show 2 or more dialog on the screen. Depends on how many times you click the button before dialog shows. So I have to close each dialog many times...
I already used dialog.isShowing but it seems that it will ignore it when you click the button quickly in multiple times.
...So I want to click button at a time when dialog is closed.
private var mFlag = false
fun myButton(view : View) {
var tempDialog = AlertDialog.Builder(this).create()
if (!mFlag) {
myDialog.show()
mFlag = true
}
if(dialog.isShowing){
mFlag = false
}
}
I have made public method for avoid double clicking issue on view.
Please check this method,
/***
* To prevent from double clicking the row item and so prevents overlapping fragment.
* **/
public static void avoidDoubleClicks(final View view) {
final long DELAY_IN_MS = 900;
if (!view.isClickable()) {
return;
}
view.setClickable(false);
view.postDelayed(new Runnable() {
#Override
public void run() {
view.setClickable(true);
}
}, DELAY_IN_MS);
}
You can use the method by following way,
buttonTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(String clickedText) {
Utils.avoidDoubleClicks(alertViewHolder.tv_alert);
// Rest code here for onlick listener
});
Or another way is,
private long lastClickTime = 0;
View.OnClickListener buttonHandler = new View.OnClickListener() {
public void onClick(View v) {
// preventing double, using threshold of 1000 ms
if (SystemClock.elapsedRealtime() - lastClickTime < 1000){
return;
}
lastClickTime = SystemClock.elapsedRealtime();
}
}

Start timer on button click

I'm new in Android programming but i know Java.
My question is, how does a timer work in Android? I've read that is better to use a handler.
What I want to do is, you click a button and the timer starts. To the moment when the button is clicked all is clear for me but how to start the timer?
How does a timer work in Android?
You better read Timer documentation, CountDownTimer Documentation and Handler Documentation.
To the moment, when the button is clicked, all is cleared for me; but, how can I start the timer?
If I didn't misunderstand your question, when you say Timer, you refer to CounteDownTimer. So, you should have something like this:
(I've written a sample code. So, you should understand it first, and then, you should apply it to your code.)
Adding the Buttons
btn1 = (Button)findViewById(R.id.bt1);
btn2 = (Button)findViewById(R.id.bt2);
Adding the SetOnClickListener()
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
});
}
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
});
}
My btn1 starts the CountDownTimer, and the second one stops and clears it.
Now, I create an Inner Class with CountDownTimerTest name.
public class CountDownTimerTest extends CountDownTimer {
public CountDownTimerTest(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
text.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("Time remain:" + millisUntilFinished);
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
}
}
Then on my btn1, I put this code (start the CountDownTimer):
countDownTimer.start();
And on my btn2, I put this code (stop/cancel the CountDownTimer):
countDownTimer.cancel();
Now, I hope that you can understand how CountDownTimer works, if your question isn't about CountDownTimer, let me know, and I'll update my answer as soon as possible with your wishes.
EDIT - Only with one Button
To do it with the same Button, you can do this:
Create a Boolean variable as:
Boolean ButtonClicked = false;
And then, modify the code as follows:
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!ButtonClicked)) {
ButtonClicked = true;
countDownTimer.start();
} else {
ButtonClicked = false;
countDownTimer.cancel();
}
});
}
EDIT 2 Get what button is clicked
You can create an int called NumberButtonClicked like this :
int NumberButtonClicked = 0;
Then on every Button you have you'll have to do this (Example) :
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
NumberButtonClicked = 1;
});
}
Then you know that if you have clicked btn1 your variable will be 1.

remove all listeners while performing some actions

I have a button (named button1) with an OnClickListener and after button is clicked, a task should be execute, and button should become unclickable until task is finished. This is my code:
#Override
public void onClick(View v) {
removeListeners();
executeMyTask();
addListeners();
}
private void disableListeners() {
button1.setOnTouchListener(null);
button2.setOnClickListener(null);
}
private void enableListeners() {
button1.setOnTouchListener(this);
button2.setOnClickListener(this);
}
Now it happen that, if I click button while executeMyTask is running (so when listener is disabled), when task finish, onClick is called again.
I would that all clicks performed while executeMyTask is running will be ignored.
how can I do ?
Why don't you just disable the whole button with:
button1.setEnabled(false);
button2.setEnabled(false);
And later just re-enable them:
button1.setEnabled(true);
button2.setEnabled(true);
It will be easier for the users to understand that the button is un-clickable at the moment.
There are 2 ways:
1) With disable all other buttons,
#Override
public void onClick(View v) {
setButtonEnabled(false);
executeMyTask();
setButtonEnabled(true);
}
private void setButtonEnabled(boolean enable) {
// TODO Auto-generated method stub
btn_1.setEnabled(enable);
btn_2.setEnabled(enable);
btn_3.setEnabled(enable);
}
2) Use a boolean to keep record of async task running or not:
Like:
#Override
public void onClick(View v) {
removeListeners();
executeMyTask();
addListeners();
}
// And in executeMyTask
onPreExecute(){
....
..
isAsyncRunning = true;
..
....
}
onPostExecute(){
....
..
isAsyncRunning = false;
..
....
}
//And in Button Click Listeners
{
if(!isAsyncRunning){
// Do something...
}
}

How can i place double click event on ImageView in Android

I have to place an double click event on Image view..Whenever I double click on Image ,It sshould be Zoom.But I found that there is no such event like double click in Image Veiw.
Can Anyone Tell me How To DO it??
Thanks in Advance..
Try this approach:
add boolean doubleClick = false;
and Handler doubleHandler
in onClick check if doubleClick is true
if true, it is a double click
if not, set doubleClick to true and use the handlers postDelayed to set it back to false after i.e. 500ms
The easiest way is to use long variable instead handler
private var doubleClickLastTime = 0L
view.setOnClickListener {
if(System.currentTimeMillis() - doubleClickLastTime < 300){
doubleClickLastTime = 0
doAction()
}else{
doubleClickLastTime = System.currentTimeMillis()
}
}
whenever the onClick() is called the new instance of Handler is created, if the Handler object is instantiated inside onClick().
So, instantiate handler outside onClick().
boolean isDoubleClicked=false;
Handler handler=new Handler();
Runnable r=new Runnable(){
#Override
public void run(){
//Actions when Single Clicked
isDoubleClicked=false;
}
}
tv.setOnClickListener(new onClickListener){
#Override
public void onClick(View view){
if(isDoubleClicked){
//Actions when double Clicked
isDoubleClicked=false;
//remove callbacks for Handlers
handler.removeCallbacks(r);
}else{
isDoubleClicked=true;
handler.postDelayed(r,500);
}
}
}
Maaalte's answer helped me to write this code.
declare doubleClick variable globally
boolean doubleClick = false;
Logic to handle double click
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Runnable r = new Runnable() {
#Override
public void run() {
doubleClick = false;
}
};
if (doubleClick) {
//your logic for double click action
doubleClick = false;
}else {
doubleClick=true;
handler.postDelayed(r, 500);
}
}
});
You may use onDoubleTapListener.
This link may hep you.

Categories

Resources