Easy way to setOnClickListener() on all Activity Buttons

后端 未结 4 1901
迷失自我
迷失自我 2021-02-06 19:07

New to android development, but not entirely new to Java. Right now my code inside the onCreate() method is quite basic:

    Button b1 = (Button) findViewById(R.         


        
相关标签:
4条回答
  • 2021-02-06 19:43

    Just a fun trick for you, since all your buttons are using the same listener, you could do something like this with less code (though it's less efficient, not likely to be noticeable though):

    ViewGroup group = (ViewGroup)findViewById(R.id.myrootlayout);
    View v;
    for(int i = 0; i < group.getChildCount(); i++) {
        v = group.getChildAt(i);
        if(v instanceof Button) v.setOnClickListener(this)
    }
    
    0 讨论(0)
  • 2021-02-06 19:47

    Create an array of buttons and do it in a loop:

    int[] ids = { R.id.button1, R.id.button2 , ........... };
    Button[] buttons = new Buttons[ids.length];
    
    for (int i = 0; i < ids.length; ++i) {
        buttons[i] = (Button)findViewByIf(ids[i]);
        buttons[i].setOnClickListener(this);
    }
    
    0 讨论(0)
  • 2021-02-06 19:52

    in onCreate call get the root layout

    ViewGroup rootLayout=(ViewGroup) findViewById(R.id.root_layout);
    

    then pass it to this method, (using recursive for deep search for buttons)

    public void setAllButtonListener(ViewGroup viewGroup) {
    
        View v;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            v = viewGroup.getChildAt(i);
            if (v instanceof ViewGroup) {
                setAllButtonListener((ViewGroup) v);
            } else if (v instanceof Button) {
                ((Button) v).setOnClickListener(myButtonsListener);
            }
        }
    }
    

    good luck

    0 讨论(0)
  • 2021-02-06 19:53

    Something a little less repetitive could be:

    int[] ids = {R.id.button1, R.id.button2, ... };
    for (int id:ids) {
        Button b = (Button) findViewById(id);
        b.setOnClickListener(this);
    }
    
    0 讨论(0)
提交回复
热议问题