Thursday, November 7, 2013

Double clicking on a button, activity launched multiple times?

Just solved this problem in a relatively nicer way across whole app.

Scenario: A button, clicking on it is supposed to launch activity A.
Problem: If you click too fast, multiple A's will be launched.

Solution: disable the button right after click. The button needs to be reenabled after the launched activity is finished though, this can be done in onResume. We could implement an Abstract base class to do this and let all classes need this logic extend this base class.

Code:
 public abstract class AvoidDoubleClickActivity extends Activity {  
      private HashSet<View> disableView = new HashSet<View>();  
      @Override  
      public void onResume() {  
           reEnableViews();  
           super.onResume();  
      }  
      protected void onViewClicked(View view) {  
           view.setEnabled(false);  
           disableView.add(view);  
      }  
      protected void reEnableViews() {  
           for (View view : disableView) {  
                view.setEnabled(true);  
           }  
           disableView.clear();  
      }  
 }  


Use case:
 public TestActivity extends AvoidDoubleClickActivity {  
   protected void foo(View view) {  
     button.setOnClickListener(new OnClickListener() {  
       @Override  
       public void onClick(View v) {  
       onViewClicked(v);  
       launchNextActivity();  
     }  
   });  
  }  
 }  

}

No comments:

Post a Comment