如何在Android中注册多个监听器?

时间:2016-01-05 10:35:39

标签: java android onclicklistener

在iOS中,我可以注册多个目标+动作事件处理程序,例如像这样的按钮:

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(20, 40, 300, 40)];
    [button setBackgroundColor:[UIColor blueColor]];
    [button setTitle:@"Click Me!" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(handler1) forControlEvents:UIControlEventTouchUpInside];
    [button addTarget:self action:@selector(handler2) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)handler1 {
    NSLog(@"Click handler 1"); // FIRES!
}

- (void)handler2 {
    NSLog(@"Click handler 2"); // FIRES!
}

@end

我希望在Java / Android中实现类似的功能,遗憾的是,只要第一个侦听器被第二个侦听器替换,它就无法工作:

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button);
    button.setText("Click Me!");
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Log.d("Test", "Click handler 1"); // DOES NOT FIRE!
      }
    });
    button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        Log.d("Test", "Click handler 2"); // FIRES!
      }
    });

  }
}

我感谢任何帮助&建议在Java / Android中实现相同的目标!

2 个答案:

答案 0 :(得分:3)

了解RxJava它是未来:) http://reactivex.io/

ViewObservable.clicks((Button) getActivity().findViewById(R.id.comment_btn))
            .compose(lifecycleMainObservable().<OnClickEvent>bindLifecycle())
            .subscribe(new Action1<OnClickEvent>() {
                @Override
                public void call(OnClickEvent onClickEvent) {
                    Log.d("Button click", "Button 1 click");
                }
            });

ViewObservable.clicks((Button) getActivity().findViewById(R.id.comment_btn))
            .compose(lifecycleMainObservable().<OnClickEvent>bindLifecycle())
            .subscribe(new Action1<OnClickEvent>() {
                @Override
                public void call(OnClickEvent onClickEvent) {
                    Log.d("Button click", "Button 2 click");
                }
            });

答案 1 :(得分:1)

在Android中处理方式是否相同,创建两种方法更简单:

button.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        method1();
        method2();
      }
    });

   private void method1(){
     Log.d("Test", "Click handler 1");
   }

   private void method2(){
     Log.d("Test", "Click handler 2");
   }

作为View.OnClickListener州的docs

  

在单击上下文视图时注册要调用的回调。如果视图不是上下文可点击的,则它将变为上下文可点击

默认情况下不会实现多个回调,但您可以自己实现。