简体   繁体   English

在一个按钮上实现多个单击侦听器

[英]implement more than one click listener on a button

I am working on an application that requires me to implement more than one click listener on a button. 我正在开发一个需要我在一个按钮上实现多个单击侦听器的应用程序。 I am stuck. 我被困住了。 After some searching, I only came across a few hacks that can make this possible. 经过一番搜索,我只遇到了一些可以使之成为可能的黑客。

However in this case, some are not applicable since in my application, the logic is that if the button is clicked and the condition is met, then the second listener is called firing off another event. 但是,在这种情况下,有些不适用,因为在我的应用程序中,逻辑是如果单击按钮并且满足条件,则第二个侦听器称为触发另一个事件。

This seems tricky. 这似乎很棘手。 Does anyone have any ideas? 有人有什么想法吗?

Thanks. 谢谢。

无需创建另一个侦听器,只需根据您的唯一侦听器的条件调用不同的函数即可。

you can meet your requirement using this: 您可以使用以下方法满足您的要求:

set a global variable say int condition_number=0; 设置一个全局变量说int condition_number=0;

then, 然后,

mButton.setOnClickListener(new OnClickListener)
{    
     performThis(condition_number);
}

perforThis(int number)
{
   switch(number) 
   {
       case 1:
              //do some stuff for condition 1
              //set condition_number accordingly,relatively to what you want to perform next
              performThis(codition_number);
              break;

       case 2:
              //do some stuff for condition 2
              //set condition_number accordingly,relatively to what you want to perform next
              performThis(codition_number);
              break;

       case 3:
              //do some stuff for condition 3
              //set condition_number accordingly,relatively to what you want to perform next
              performThis(codition_number);
              break;

       default:
               //do something
               break;
   }
}

This way,you would be able to call different code snippets for different condition and repeatedly call them as you require without making conflict. 这样,您将能够针对不同的条件调用不同的代码段,并根据需要重复调​​用它们而不会造成冲突。

You can set a case to get out of the execution of this method by just putting break there. 您可以设置一个大小写,以使其脱离该方法的执行范围,只需在其中放置中断即可。

在此线程上尝试检查的答案,也许这就是您要查找的内容- 在一个类中保留多个OnClickListener

As pointed out by shadow, you can do something like that: 如阴影所示,您可以执行以下操作:

your XML layout: 您的XML布局:

<Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="@string/doStuff"
     android:onClick="doStuff" />

in your activity: 在您的活动中:

function void doStuff(View target) {
   listener1(target);
   listener2(target);
   ...
}

function void listener1(View target) {
   ...
}

function void listener2(View target) {
   ...
}

And then implement your multiple listeners in listener1, listener2, etc... 然后在listener1,listener2等中实现您的多个侦听器...

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

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