android – How to get all buttons at once?-ThrowExceptions

Exception or error:
Button button = findViewById(;

That’s the only way I know to get the button, but I have 45 buttons and it’s too hard for me to get the buttons one by one.

Is there is any way to get all the buttons at once?

How to solve:

If you have 45 buttons on the screen, I’m thinking maybe you need to use a RecyclerView, to display one button, and then duplicate it a lot of times.
Their click listener will depend on the button index.


as far as i understood your question i think you can find your answer on this post.
How to get all Buttons ID's in one time on Android


You can try something like

val root = findViewById<ViewGroup>(

val buttons =  (0 until root.childCount)
                    .mapNotNull { root.getChildAt(it) as? Button }

in onCreate of your activity

Leave a Reply

Your email address will not be published. Required fields are marked *