Finding a button added to TableRow by id in OnLongClick in Android?
I have a TableLayout with dynamically added TableRows depending on the size of a cursor.
To each row I add a Delete-button, which is set to Invisible. Each row and button gets an id on creation that is the same if then belong to the same row.
WHen the user LongClicks on the TableRow the visibility is set to Visible
instead and the Delete-button appears.
In the OnLongClick
listener I check if the button Id is the same as the view (Here TableRow) that was clicked on.
rel.addView(btnDelete);
tr.addView(rel);
tr.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
int tableRowId = view.getId();
if(tableRowId == btnDelete.getId()){
btnDelete.setVisibility(View.INVISIBLE);
}
return true;
}
});
But it only seems to be true for the button on the bottom lowest button. So then it seems like the btnId
is stored as the last btnId
added, since the only TableRow
it is true for is the last one. But when i use .setText(btnId + t开发者_如何转开发ableRowId)
I can see they have the same id all the way down.
I tried to use Tag as well, but I stumble on the same problem.
Thanks alot!
Edit:
btnDelete = new Button(this);
btnDelete.setId(revolutionCounter);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,
RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_VERTICAL);
btnDelete.setLayoutParams(params);
rel.addView(btnDelete);//a relativelayout inside the tablerow
tr.addView(rel);
Then I add the tr (tablerow) to the tablelayout. So I guess I am reusing the buttons? How should I go about it creating new ones? I thought that was what I was doing with the new Button(this);
Several solutions
- Instead of capturing the longclick on the table row, capture it directly on the delete button by doing
btndelete.setDuplicateParentStateEnabled(true)
Button.setDuplicateParentStateEnabled(boolean)
Add a LongClickListener on btnDelete and set the visibility to Visible/invisible, toggle it or whatever you want to do. If you need to access the table row inside the longclickListener, call
TableRow tableRow = (TableRow) view.getParent();
If you want to keep the longclicklistener on the TableRow, you can access its btnDelete child this way:
Button btnDelete = view.findViewById(view.getId());
PS. Not sure if this is a problem, but you are still destroying previous delete buttons. Instead of
btnDelete = new Button(this);
you need to redeclare it
Button btnDelete = new Button(this);
Maybe this isn't important and probably each row stores the value of the button object (otherwise it wouldn't even display), but in other situations this has given me some headaches. In this case maybe it's okay to reuse the variable declaration.
精彩评论