Android - multiple OnClickListener?

前端 未结 5 2314
-上瘾入骨i
-上瘾入骨i 2021-02-20 03:39

I have 4 images. We should be able to click on these images. I\'d like to know if I have to create 4 OnClickListener, or there is another way to do this properly?

5条回答
  •  死守一世寂寞
    2021-02-20 03:56

    You can use/make your listener this way:-

    img1.setOnClickListener(imgClk);
    img2.setOnClickListener(imgClk);
    img3.setOnClickListener(imgClk);
    img4.setOnClickListener(imgClk);
    

    And then you have to create OnClickListener after onCreate/out side of onCreate()

        public OnClickListener imgClk = new OnClickListener() 
            {
                @Override
                public void onClick(View v) 
                {
                  switch(v.getId()){
                    case R.id.img1:
                     //write your code here
                      break;
    
                   case R.id.img2:
                     //write your code here
                      break;
    
                   case R.id.img3:
                     //write your code here
                      break;
    
                   case R.id.img4:
                     //write your code here
                      break;
               }
           };
    

    I hope it helps you.

提交回复
热议问题