I'm dynamically adding/deleting rows, each row has several buttons including a button to delete the row.
Each row represents an item of an ArrayList (I have an ArrayList which is being used to store the list of row data).
When adding each row, I add an onClickListener for the delete button:
private ArrayList<item> ItemList = new ArrayList<>();
void AddRow(item item, int index){
ItemList.add(item);
LinearLayout llItem = findViewById(R.id.llItem);
View rowview = inflater.inflate(R.layout.cardrow, null);
ImageButton btnDelete = rowview.findViewById(R.id.btnDelete);
btnDelete.setOnClickListener(new View.OnClickListener(){
@Override public void onClick(View v){
list.remove(index); // <--- This is the problem, it is not dynamic
llItem.removeView((View) v.getParent());
}
});
llItem.addView(rowview, llItem.getChildCount());
}
The list.remove(index) shifts the indices of the lower rows, so that their onClickListeners may not be accurate. For example: if I add 3 rows, click the delete button of the 1st row, then the last row points to an index that is now outofbounds.
What is the best way to fix this and make it dynamic?
Is there some way I can do something like v.getIndex(), to get the real index of the row in the view?