How to identify the button clicked from a dynamically generated table

android, user-interface

Solution

You can set an `onClickListener` listener for each button. Use the id of the button from `view.getId()` method on your `onClick()` method to identify the button click.

You can add separate listeners for each button like here (assuming that the id you are setting for each button corresponds to a row)

minusButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
             // Do some operation for minus after getting v.getId() to get the current row
        }
    }
);

Edit:

I am assuming your code is like this. Correct me if there is a deviation.

Button minusButton = null;
for(int i = 0; i < rowCount; i++)
{
    minusButton = new Button(this);
    minusButton.setId(i);
    // set other stuff and add to layout
    minusButton.setOnClickListener(this);
}

Let your class implement the interface `View.OnClickListener` and implement the `onClick()` method.

public void onClick(View v){
    // the text could tell you if its a plus button or minus button
    // Button btn = (Button) v;
    // if(btn){ btn.getText();}
    // getId() should tell you the row number
    // v.getId()
}

Problem

I am populating a table dynamically from a string array.Each row of the table also has a plus and minus button to increment/decrement the value of one column. These buttons are also dynamically created like in the code below. Here how can I detect the exact button upon clicking. i.e; if I click on the '+' button of the 2nd row, how can I get the id of the button clicked for further processing. ``` plusButton= new Button(this); minusButton= new Button(this); createView(tr, tv1, names[i]); createView(tr, tv2, (String)(names[i+1])); minusButton.setId(i); minusButton.setText("-"); minusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); plusButton.setId(i); plusButton.setText("+"); plusButton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));` ```

Original source