Android Button on ClickLinstener

Asked 2 years ago, Updated 2 years ago, 44 views

We have created 25 buttons dynamically as follows: Now, I want to attach an on-click listener to each button, but I want to get rowCounter and columnCounter as a factor.

I don't know where to access the button because it's not made on xml.

I want to use only one listener because each button has the same work.

git github android

2022-09-22 21:30

1 Answers

There is no direct way to know row and column in the current state. Additional implementation is required to know this information. I think there are several ways, but I wrote down the first thought that came to mind in code. (This is not a complete code, just refer to the implementation)

The code you uploaded uses the list, not the 2D array.

List<ImageButton> buttons = new ArrayList<>();
for (int row = 0; row < DIMENSION; row++) {
    for (int column = 0; < column < DIMENSION; column++) {
        ImageButton button = new ImaegButton(this);
        ...
        button.setOnClickListener(this);
        buttons.add(imageButton);
    }
}

The next part is the Click Listener. This is a method of calculating row and column using the currently clicked View index in the list.

@Override
public void onClick(View v) {
    int index = buttons.indexOf(v)
    int row = index / 3;
    int column = index % 3;

    // Do the desired processing with the row and column obtained above.
}


2022-09-22 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.