0

I'm making a calculator for just a practice, but I found that there are so many buttons. I named their id like button+row+col ex) row=5, col=4 -> id=button54

Since I have to attack listener to every button, I found it very annoying things to do this manually. Like,

findViewById(R.id.button11).setOnClickListener(this);
findViewById(R.id.button12).setOnClickListener(this);
...
findViewById(R.id.button95).setOnClickListener(this);

Can I do this like

for(int i=1; i<=9; i++){
    for(int j=1; j<=5; j++){
        findViewById(R.id."button"+Integer.toString(i) + Integer.toString(j)).setOnClickListener(this);
    }
}

or other way to make this easier.

enter image description here

김선달
  • 1,485
  • 9
  • 23

3 Answers3

1

You can't do that. 2 possibilities :

  • create an Array with yours ID, to be able to use a for loop
  • use ButterKnife with @BindViews annotation
Bruno
  • 3,872
  • 4
  • 20
  • 37
1

Since you're working with a lot of buttons I suggest you put them all into a ViewGroup (like LinearLayout, FrameLayout or something like that), then iterate through each View of that ViewGroup, check its instance then assign the click listener.

Here is some pseudo-code since I forgot how Java works

ViewGroup viewGroup = findViewById(R.id.yourViewGroupName);
for each child in viewGroup.getChildren {
    if child is of type Button {
        child.setOnClickListener(this);
    }
}
Zun
  • 1,553
  • 3
  • 15
  • 26
  • Here some actual code to get children of a View: https://stackoverflow.com/questions/8395168/android-get-children-inside-a-view/11263152#11263152 – Zun Jul 22 '19 at 08:03
-1

I think you should add an onClick "ID" in your xml and let Android Studio do the work.

<Button
        android:id="@+id/bt_54"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:clickable="true"
        android:focusable="true"

        android:onClick="oc_bt_54"
        />

and now in your xml file hover over the onClick, which should be underlined red and go to the red light bulb on the left. Your Option: Creat Method in Activity xy.

and now in your Activity you will see:

 public void oc_bt_54(View view) {

    }

No need for findViewByID(). Very easy and clean solution.

(Tip: if you need the onClick method created in a special Activity, use:

tools:context=".your_special_Activity"

in the main layout of your xml.)

Alpha-Centauri
  • 316
  • 2
  • 13