9

I want to use existing onClick method to make my program simpler. It consists of onClick method and other method:

@Override
public void onClick(View v) {
  switch(v.getId()){
  case R.id.button1:
    ....
    break;
  }
}

void foo(){
  ....
  onClick(????);
}

Is there any way to make it do the same behaviour like when i click it on the phone?

Victorio Pui
  • 358
  • 1
  • 3
  • 11

4 Answers4

24

you can use View.performClick()

reference

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
Iftikar Urrhman Khan
  • 1,131
  • 1
  • 10
  • 21
2

performClick() will play a sound just like if the user clicked on that view, therefore in most cases it's better to use callOnClick(), which will call the OnClickListener without playing any click sound. (Available since API level 15)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) myView.callOnClick(); //won't play sound
else myView.performClick(); //will play sound
steliosf
  • 3,669
  • 2
  • 31
  • 45
0
Handler handler = new Handler(  );
    handler.postDelayed( new Runnable() {
        @Override
        public void run() {
            // call the method below
        }
    },0 );
-1
public class DemoActivity extends AppCompatActivity implements View.OnClickListener{         

Button mBtnAutomaticClick;
        protected void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.activity_report_bug);
             mBtnAutomaticClick = findViewById(R.id.automatic_click_demo);
             mBtnAutomaticClick.setOnClickListener(this);
             mBtnAutomaticClick.performClick(); // for automatic click event
          }
      }

@Override
public void onClick(View v) {
     switch (v.getId()) {
        case R.id.automatic_click_demo:
           // your code
           break;
    }
}

When activity will call your code which you have written inside onClick will be called automatically.

Harsh Prajapati
  • 510
  • 5
  • 7