Home » Android » Android – attach data to views

Android – attach data to views

Posted by: admin April 23, 2020 Leave a comment


In my application I create dynamic rows in table much as in this tutorial:

 for(int i = startDay; i < startDay + 7; i++){

      /* Create a TextView to be the row-content. */
      TextView day = new TextView(this);
      day.setLayoutParams(new LayoutParams(

      day.setOnClickListener(new OnClickListener() {
          public void onClick(View v) {
              Log.i("Listener: ", "Click");

So now when I click on a TextView I can register click event, but how do I determine which TextView was clicked?

Not just an object which I get with an event but data like which day number was clicked?

Ideally I would want to have data attached to every view I create dynamically.
Something like data() method in Javascript jQuery.

Right now I can see only 1 way to solve this – while creating TextView add id with data and when clicked – get id back and parse it to get my data. But it strikes me as ugly approach.

Is there a way to attach arbitrary data to android views?

How to&Answers:

Found answer going through view methods. Maybe it will be useful for someone.

Methods I needed were:

setTag() and getTag()