performClick

In Android, View.performClick is defined as:

/**
 * Call this view's OnClickListener, if it is defined.  Performs all normal
 * actions associated with clicking: reporting accessibility event, playing
 * a sound, etc.
 *
 * @return True there was an assigned OnClickListener that was called, false
 *         otherwise is returned.
 */
public boolean performClick()

Using calling method, view’s OnClickListener can be tested. More commonly, this is used to invoke view click through code. For example, a search button can be clicked when a enter key is entered.

searchText.setOnKeyListener(new OnKeyListener() {
  @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP ) {
        searchButton.perfomClick();
        return true;
      }
    return false;
  }
});

If you use this method, it works mostly well like you expected. However, I’ve noticed that some people often have a problem because they forgot its definition. What do you expect about this example?

searchButton.setOnClickListener(searchButtonClickListener);
searchButton.setEnabled(false);
searchButton.performClick();

searchButton is disabled. Thus, you might think that searchButtonClickListener is not called when performClick method is called. Actually, it is called. How about this example?

searchButton.setOnClickListener(searchButtonClickListener);
searchButton.setClickable(false);
searchButton.performClick();

This also calls searchButtonClickListener. Let’s see the definition again. It says that this method calls view’s OnClickListener. In short, it doesn’t care the view’s status. However, users will not reach OnClickListener if a view is disabled(or not clickable).

You now understand the difference between performClick and users click. If you call the performClick in order to mimic a user’s click, I suggest to use this helper method.

public static boolean performClick(View view) {
  return view.isEnabled() && view.isClickable() && view.performClick();
}