Bitle Apps Bitle Apps - 5 months ago 17
Android Question

Detect which button was pressed - Android

Here's my situation:
I programmatically give some buttons an onClickListener, however, I can't fully-handle this event, because I'd like to detect which button was pressed to give to that button (when it is pressed) a new value. Here's how I program those buttons:

final View.OnClickListener soundButtonListener = new View.OnClickListener() {
public void onClick(View v) {
playSound(1);

int x = songPlay * songProgress;

mplayer.seekTo(x);
}
};

tableLayout = (TableLayout)v
.findViewById(R.id.tableLayout);

int number = 1;
for (int i = 0; i < tableLayout.getChildCount(); i++) {
TableRow row = (TableRow)tableLayout.getChildAt(i);
for (int j = 0; j < row.getChildCount(); j++) {
Button button = (Button) row.getChildAt(j);
button.setText("" + number);

button.setOnClickListener(soundButtonListener);
songProgress = j;
number++;
}
}


As you see, they haven't a click listener for each one, so when I press my button, mplayer always seekto a point, becausae songProgress stops at 64 (I have 64 buttons to handle). What is good is that I have a number for each button (as you see button.setText("" + number);), and I'd like to check what is their number to give to songProgress different values.

I hope I was clear. Thanks in advance

--- Update ---

if (v instanceof Button) {

Button button = (Button) v;
String text = button.getText().toString();
Integer number = (Integer) v.getTag();
if (number != null) {
int x = songPlay * number;
try {
mplayer.seekTo(x);
} catch (Exception e) {
e.printStackTrace();
}
playSound(1);
}
}


Finally solved using this code, I needed to clean the project.

Answer

If i correctly understand you can do something like this:

final View.OnClickListener soundButtonOnClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if(v instanceof Button) {
            Button button = (Button) v;
            String text = button.getText().toString();

            if(text == "1") {
                //...
            } else if(text == "2") {

            }
            //OR
            switch (text) {
                case "1": {
                    break;
                }
                case "2": {
                    break;
                }
                //...
            }
        }
    }
};

But in my opinion better use tag instead of text:

//set tag for your button
button.setTag(number); 

//use this tag
Integer number = (Integer) v.getTag();
if(number != null) {
    //...
}