[英]How can I call to a button Event Listener. even is not clicked?
I have button event listener with some actions inside which work good. 我有一些事件的按钮事件侦听器,其中的工作很好。 I want to execute that event listener even I don't press that button I mean like execute a normal method. 我想执行该事件侦听器,即使我不按该按钮,我的意思是像执行常规方法一样。 Because I don't want to copy and paste the same code. 因为我不想复制和粘贴相同的代码。 How can I do it? 我该怎么做?
Thank you! 谢谢!
Anonymous classes you create have access to methods in the surrounding class. 您创建的匿名类可以访问周围类中的方法。 I'm assuming you have an Activity with some code like this: 我假设您有一个带有以下代码的Activity:
Button button = (Button) findViewById(R.id.mybutton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// do stuff here
}
});
Instead, add a method to your Activity, say private void doButtonStuff()
. 相反,向您的Activity添加一个方法,例如private void doButtonStuff()
。 Then set up your OnClickListner
so the onClick
method looks like this: 然后设置您的OnClickListner
以便onClick
方法如下所示:
public void onClick(View v) {
doButtonStuff();
}
Now you can call doButtonStuff()
without having to trigger the listener. 现在,您可以调用doButtonStuff()
而不必触发侦听器。
Alternatively you could programatically click the button: 或者,您可以通过编程方式单击按钮:
Button button = ...
button.performClick()
This fires the attached OnClickListener, and makes it look and sound like the button was clicked. 这将触发附加的OnClickListener,并使其外观和声音像单击按钮一样。 I think extracting the code into a method sounds like a better solution for your situation though. 我认为将代码提取到方法中听起来像是针对您情况的更好解决方案。
刚打电话
View.performClick();
If you want to this the best way would be to put all those actions that are placed inside the eventlistener together in a method and then call this method inside your eventlistener and outside whenever you want. 如果要这样做,最好的方法是将所有放置在事件侦听器中的动作放到一个方法中,然后在需要时在事件侦听器内外调用此方法。 This is the best way so you can use this actions wherever you want. 这是最好的方法,因此您可以在任何地方使用此操作。 Hope this helps! 希望这可以帮助!
in Java8 I found that the programmatically 'click' is: 在Java8中,我发现以编程方式“点击”为:
buttonName.doClick();
and NOT 并不是
buttonName.performClick();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.