简体   繁体   English

如何在Android中重用onClickListener

[英]How can reuse onClickListener in Android

I'm having one activity containing many buttons and each button performs different task. 我有一个包含许多按钮的活动,每个按钮执行不同的任务。 Since, I'm using push notifications to perform separate task every time for different notification, What is the best way to simulate the onClick Event. 因为,我每次都使用推送通知执行单独的任务以进行不同的通知,模拟onClick事件的最佳方法是什么。

One way I thought is using function. 我认为使用功能的一种方法。 Writing separate function and calling it in onClickListener. 编写单独的函数并在onClickListener中调用它。 Is there any other way to achieve the objective? 有没有其他方法来实现目标?

  btnengg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            if (netconnect(null)==1)
            {
                w.loadUrl("myurl1");
                wtshare.setVisibility(View.VISIBLE);
            }

            else
            {
            mInterstitialAd.show();

            pbb.setVisibility(View.VISIBLE);
            fadView.setVisibility(View.INVISIBLE);
            w.loadUrl("myurl2");
                requestNewInterstitial();

            }}
    });

Assign OnClickListener to a field and set it as click listener and based on button Id perform relative action 将OnClickListener分配给字段并将其设置为单击侦听器,并根据按钮Id执行相对操作

OnClickListener buttonClickListener = button -> {
    switch (button.getId()) {
        case R.id.button1:
            break;
    }
};

button.setOnClickListener(buttonClickListener);

In case you are asking how to initiate click action programmatically, you can button.performClick(); 如果您询问如何以编程方式启动单击操作,则可以按钮.performClick();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM