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

3 Answers 3

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);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Here some actual code to get children of a View: stackoverflow.com/questions/8395168/…
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

1 Comment

I have to declare all buttons first with both the array method and butterknife.
-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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.