Search code examples
javaandroidtagscustom-adapter

How to set a tag to a row in a custom adapter Android Studio Java


I am trying to set a tag to the row (or at least something in the row, preferably the row though). Then when I click on the row, I can get the tag. I thought that this is what I have to do, but the tag is always null, regardless of what I tap on.

My code example shows my attempt at setting a tag to a textview, as I have no idea how to set it to the row.

This is my getView code in my customAdapter class

int counter = 0;

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater layoutInflater = LayoutInflater.from(getContext());

    View customView = layoutInflater.inflate(R.layout.my_row, parent, false);

    ViewHolder holder = new ViewHolder();

    holder.name = (TextView)customView.findViewById(R.id.nameTextView);
    holder.picture = (ImageView)customView.findViewById(R.id.pictureImageView);

    holder.name.setText(allNames.get(position));
    holder.picture.setImageResource(allPictures.get(position));

    //This does not work ---> holder.name.setTag(counter);

    counter ++;
    return customView;
}

This is my onClickListener in a different class

listVIew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, final int position, long l) {

           Toast.makeText(getApplicationContext(), "tag is " + view.getTag(), Toast.LENGTH_SHORT).show();

        }
    });

Any help would be appreciated. Thanks.


Solution

  • Try this,

    @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            LayoutInflater layoutInflater = LayoutInflater.from(getContext());
    
            View customView = layoutInflater.inflate(R.layout.my_row, parent, false);
    
            ViewHolder holder = new ViewHolder();
    
            holder.name = (TextView)customView.findViewById(R.id.nameTextView);
            holder.picture = (ImageView)customView.findViewById(R.id.pictureImageView);
    
            holder.name.setText(allNames.get(position));
            holder.picture.setImageResource(allPictures.get(position));
    
            //This does not work ---> holder.name.setTag(counter);
    
            customView.setTag(Integer.valueOf(counter));
    
            counter ++;
            return customView;
        }