Android - OnClick Listener在一个单独的类 [英] Android - OnClick Listener in a separate class
问题描述
是否可以创建一个辅助类来保存OnClick侦听器?没有在Activity类中创建含义?
Is it possible to make a secondary class to hold the OnClick Listener? Meaning not being created in the Activity class?
我只是发现将OnClick监听器放在主活动类中只是凌乱,我宁愿将它们放在单独的类中。感谢
I just find that putting OnClick listeners in the main activity class is just messy and I would rather have them in separate classes. Thanks
推荐答案
当然可以。只需创建一个实现 View.OnClickListener
的类,并将其设置为 View
。例如:
Sure, that's possible. Just create a class that implements View.OnClickListener
and set that as listener to the View
. For example:
public class ExternalOnClickListener implements View.OnClickListener {
public ExternalOnClickListener(...) {
// keep references for your onClick logic
}
@Override public void onClick(View v) {
// TODO: add code here
}
}
然后将上面类的实例设置为listener :
And then set an instance of above class as listener:
view.setOnClickListener(new ExternalOnClickListener(...));
参数化构造函数是可选的,但很可能你需要传递一些东西, onClick(...)
逻辑工作。
The parameterized constructor is optional, but it's very likely you'll need to pass something through to actually make your onClick(...)
logic work on.
匿名实现类通常更容易使用。只是一个想法。
Implementing a class anonymously is generally easier to work with though. Just a thought.
这篇关于Android - OnClick Listener在一个单独的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!