How to identify a button clicked from a dynamically created table

I am dynamically populating a table from an array of rows. Each row of the table also has a plus and minus button to increase / decrease the value of one column. These buttons are also dynamically created, as in the code below. Here is how I can determine the exact button when clicked. i.e; if I press the "+" button of the second row, how can I get the identifier of the button pressed 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));` 
+4
source share
2 answers

You can set the onClickListener for each button. Use the button identifier from the view.getId() method using the view.getId() method to identify the button click.

You can add separate listeners for each button, as here (provided that the identifier that you set for each button matches the line)

 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 assume 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 View.OnClickListener interface 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() } 
+2
source

You can do with tags: minusButton.setTag("-") and plusButton.setTag("+") .

In your clickListener, just get it using the view.getTag() button.

Then switch between your actions by comparing the string tag.

Edit:
The identifier "must" be unique. The setTag () method can help you if setId () does not work for you.

0
source

All Articles