Easy way to setOnClickListener() on all Activity Buttons

后端 未结 4 1897
迷失自我
迷失自我 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: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);
    }
    

提交回复
热议问题