Android - Reduce the setOnClickListener () functions

0

It turns out that I have 2 menus on the screen, one horizontal and one vertical made with Linearlayouts, and at least I have 15 buttons. My query is ... Is there any pattern or optimization that you use so that you do not have to do the setOnClickListener in onCreate ()?

For example, before I used a Toolbar with a menu, then easily with an item.getItemId () and a switch solved it. But now I have to one by one relate the view with the controller and to each one set an OnCLickListener, and I seem to be repeating a lot of code since in OnClick I only call another function.

I hope you can help me! Thanks!

    
asked by Leandro Gutierrez 04.02.2018 в 21:19
source

1 answer

0

Personally and although it might not be the best option, you could use a List of Button 's, each button identifier within an array to create the object, and then add it to the list , then you implement the interface View.OnClickListener to assign specific events to certain id's or as you mention call a function by default, here's the example:

public class ActivityMain extends Activity implements View.OnClickListener
{ 
    private List<Button> buttons;
    private static final int[] BUTTONS = {
        R.id.button1,
        R.id.button2, 
        R.id.button3,
        R.id.button4,
        R.id.button5,
        R.id.button6
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tuview);

        buttons = new ArrayList<Button>();

        for(int id : BUTTONS) {
            Button button = (Button)findViewById(id);
            button.setOnClickListener(this);
            buttons.add(button);
        }
    }
    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {
          case R.id.button1: //id's especificos
              //Tu metodo
              break;
          default:
              //Metodo por defecto
              break;
        }
    }

}
    
answered by 04.02.2018 / 22:41
source