김선달
김선달

Reputation: 1562

android studio(java) finding view id with string

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

Upvotes: 0

Views: 164

Answers (3)

Alpha-Centauri
Alpha-Centauri

Reputation: 336

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.)

Upvotes: -1

Zun
Zun

Reputation: 1710

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);
    }
}

Upvotes: 1

Bruno
Bruno

Reputation: 4007

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

Upvotes: 1

Related Questions