Reputation: 14783
I'm inflating a view, setting it's ID, set some tags, set an onClickListener on it and add it to a parent view.
LinearLayout llCategoryListIncome = (LinearLayout)calculatorFlipContainerBack.findViewById(R.id.ll_category_list_income);
// inflate category item
LinearLayout categoryItem = (LinearLayout)inflater.inflate(
R.layout.fragment_category_item,
container,
false);
Integer id = 2;
Integer position = 3;
categoryItem.setId(position);
categoryItem.setTag(R.string.tag_category_position, position);
categoryItem.setTag(R.string.tag_category_id, id);
categoryItem.setOnClickListener(this);
llCategoryListIncome.addView(categoryItem);
In the onClick Listener I want to check this ID. But the ID is always -1. Same issue with the tags. The tags are always null.
public void onClick(View v) {
Integer position = (Integer)view.getTag(R.string.tag_category_position);
Integer id = (Integer)view.getTag(R.string.tag_category_id);
Log.d(TAG, "view get id " + view.getId()); // is null
Log.d(TAG, "position is " + position); // is null
Log.d(TAG, "id is " + id); // is -1
Any idea what could be wrong?
Upvotes: 0
Views: 116
Reputation: 103
I suggest you to define and use a holder inside your code.
private class TagHolder
{
int id; int position;
}
TagHolder tagHolder = new TagHolder();
tagHolder.id = 2;
tagHolder.position = 3;
view.setTag(tagHolder);
public void onClick(View v) {
TagHolder tagHolder = (TagHolder)view.getTag();
// tagHolder.id, tagHolder.position
}
Upvotes: 0
Reputation: 52790
Why you call setTag twice ?
you have to setTag once by below line:
categoryItem.setTag(position);
Onclick method
Integer id = (Integer)view.getTag();
Log.d(TAG, "id is " + id);
Done
Upvotes: 0
Reputation: 948
You must use id and not string resource when you assign a Tag.
Use something like
categoryItem.setTag(R.id.your_id_for_position, position);
instead of
categoryItem.setTag(R.string.tag_category_position, position);
As said in the View class documentation
The specified key should be an id declared in the resources of the application to ensure it is unique
Upvotes: 1