Easy way to setOnClickListener() on all Activity Buttons

后端 未结 4 1898
迷失自我
迷失自我 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: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

提交回复
热议问题