android中的onclick监听器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3505841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 10:30:21  来源:igfitidea点击:

onclick listener in android

androidonclicklistener

提问by sivaraj

I used two image button for Next and Back and i used onclick event for those button i want to which image button fire on onclick and run particular function for next or back in onclick event how will i get which image button fire or onclick event at runtime

我为 Next 和 Back 使用了两个图像按钮,我对那些按钮使用了 onclick 事件,我希望哪个图像按钮在 onclick 时触发,并在 onclick 事件中为 next 或 back 运行特定功能,我将如何在运行时触发哪个图像按钮或 onclick 事件

回答by Konstantin Burov

Use View.getId() to distinguish between different views that fire onClick events.

使用 View.getId() 来区分触发 onClick 事件的不同视图。

@Override
public void onClick(View view) {
    switch (view.getId()) {
    case R.id.download:
    //code..
    break;
    case R.id.play:
    //code..
    break;
    case R.id.pause:
        //code..
    break;
    default:
        //code..
    break;
    }
}

回答by Cheryl Simon

You can use anonymous inner classes to write an onClick function for each button.

您可以使用匿名内部类为每个按钮编写一个 onClick 函数。

Button button1 = getMyButton();
button1.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      // button 1 was clicked!
   }
  });
Button button2 = getMyButton();
button2.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
      // button 2 was clicked!
   }
  });

As Konstantin mentioned, you can also use the passed in View and switch on the id. However, I find that a bit messier if you end up with lots of clickable things.

正如 Konstantin 所提到的,您还可以使用传入的 View 并打开 id。然而,我发现如果你最终得到很多可点击的东西,那就有点麻烦了。