I am trying to prevent the activity from loading twice if I press the button twice instantly after the first click.
I have an activity which loads on click of a butt
I think you're going about solving the problem the wrong way. Generally it is a bad idea for an activity to be making long-running web requests in any of its startup lifecycle methods (onCreate()
, onResume()
, etc). Really these methods should simply be used to instantiate and initialise objects your activity will use and should therefore be relatively quick.
If you need to be performing a web request then do this in a background thread from your newly launched activity (and show the loading dialog in the new activity). Once the background request thread completes it can update the activity and hide the dialog.
This then means your new activity should get launched immediately and prevent the double click from being possible.
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
myButton.setOnClickListener(null);
}
});
Use a flag
variable set it to true
,
Check if its true just return
else perform Activity Call.
You can also use setClickable(false) one executing the Activity Call
flg=false
public void onClick(View view) {
if(flg==true)
return;
else
{ flg=true;
// perform click}
}
add Launch Mode as single task in manifest to avoid activity opening twice on clicking
<activity
android:name=".MainActivity"
android:label="@string/activity"
android:launchMode = "singleTask" />
Since SO doesn't allow me to comment on other answers, I have to pollute this thread with a new answer.
Common answers for the "activity opens twice" problem and my experiences with these solutions (Android 7.1.1):
EDIT: This was for starting activities with startActivity(). When using startActivityForResult() I need to set both FLAG_ACTIVITY_SINGLE_TOP and FLAG_ACTIVITY_CLEAR_TOP.
Other very very simple solution if you no want use onActivityResult()
is disable the button for 2 seconds (or time you want), is not ideal, but can solve partly the problem is some cases and the code is simple:
final Button btn = ...
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//start activity here...
btn.setEnabled(false); //disable button
//post a message to run in UI Thread after a delay in milliseconds
btn.postDelayed(new Runnable() {
public void run() {
btn.setEnabled(true); //enable button again
}
},1000); //1 second in this case...
}
});