Easy way to setOnClickListener() on all Activity Buttons

后端 未结 4 1900
迷失自我
迷失自我 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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)
    }
    

提交回复
热议问题