Android call onClick method without Clicking

倖福魔咒の 提交于 2019-12-05 09:45:01
Iftikar Urrhman Khan

you can use View.performClick()

reference

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
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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!