onclick listener in android

后端 未结 2 664
春和景丽
春和景丽 2020-12-10 06:40

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

相关标签:
2条回答
  • 2020-12-10 07:09

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

    @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;
        }
    }
    
    0 讨论(0)
  • 2020-12-10 07:14

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

    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.

    0 讨论(0)
提交回复
热议问题