Best way to implement View.OnClickListener in android

后端 未结 14 2414
盖世英雄少女心
盖世英雄少女心 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:12

    First, there is no best practice defined by Android regarding registering click listeners. It totally depends on your use case.

    Implementing the View.OnClickListener interface to Activity is the way to go. As Android strongly recommends interface implementation over and over again whether it is an Activity or Fragment.

    Now as you described :

    public class ActivityMain extends Activity implements View.OnClickListener
    {
        private class ClickListener implements View.OnClickListener
        {   
            @Override
            public void onClick(View view)
            {
                switch (view.getId())
                {
                    //handle multiple view click events
                }
            }
        }
    }
    

    This is your approach. Now it is your way of implementation and there is nothing wrong with this if you are not concerned with memory overhead. But what's the benefit of creating the inner class and implementing the View.OnClickListener if you can simply implement that in the main class which can also lead to the code clarity and simplicity that you need.

    So it just a discussion rather getting the best possible solution of implementing the View.OnClickListener because if you go with the practical point of everyone, you will go for a solution which is simple and memory efficient.

    So I would prefer the conventional way. It keeps things simple and efficient. Check the code below:

    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {
            //handle multiple view click events
        }
    }
    

    P.S : Your approach will definitely increase lines of code :P ;)

提交回复
热议问题