Best way to implement View.OnClickListener in android

后端 未结 14 2437
盖世英雄少女心
盖世英雄少女心 2020-11-27 05:25

Suppose we have an Activity with a lot of views on which OnClickListener is to be registered.

The most common way to implement this is to let the Activi

14条回答
  •  悲&欢浪女
    2020-11-27 06:06

    Here you can create a btnClickListner object and after that you will call that btnCLickLisner object when ever you want to perform the onCLieck actions for buttons..

    Let us assume, in my activity i have a 5 to 10 buttons and writing each button separate onclick listner is bad idea. So to over come this,we can use like below..

    register your buttons

    Button button1 = (Button)findViewById(R.id.button1);
    Button button2 = (Button)findViewById(R.id.button2);
    Button button3 = (Button)findViewById(R.id.button3);
    Button button4 = (Button)findViewById(R.id.button4);
    Button button5 = (Button)findViewById(R.id.button5);
    

    Here i am setting the onclick listner to my buttons after click

    button1.setOnClickListener(btnClickListner);
    button2.setOnClickListener(btnClickListner);
    button3.setOnClickListener(btnClickListner);
    button4.setOnClickListener(btnClickListner);
    button5.setOnClickListener(btnClickListner);
    

    Here is the btnClick Listner implementation

    View.OnClickListener btnClickListner = new OnClickListener()
        {
      @Override
            public void onClick( View v )
            {
                // TODO Auto-generated method stub
                if( button1.getId() == v.getId() )
                {
                    //Do Button1 click operations here
    
                }
                else if( button2.getId() == v.getId() )
                {
    
                   // Do Button2 click operations here
    
                }
                else if( button3.getId() == v.getId() )
                {
                     // Do Button3 click operations here
    
                }
                else if( button4.getId() == v.getId() )
                {
                    // Do Button4 click operations here
    
                }
                else if( button5.getId() == v.getId() )
                {
                    // Do Button5 click operations here
                }
    
            }
    
         }
    

提交回复
热议问题