Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - attach data to views

In my application I create dynamic rows in table much as in this tutorial: http://en.androidwiki.com/wiki/Dynamically_adding_rows_to_TableLayout

 for(int i = startDay; i < startDay + 7; i++){        /* Create a TextView to be the row-content. */       TextView day = new TextView(this);       day.setText(Integer.toString(i));       day.setLayoutParams(new LayoutParams(                 LayoutParams.FILL_PARENT,                 LayoutParams.WRAP_CONTENT));        day.setOnClickListener(new OnClickListener() {           @Override           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?

like image 584
Leonti Avatar asked Apr 22 '10 21:04

Leonti


People also ask

How do you bind data?

To convert your XML layouts into the Data Binding layout, follow the below steps: Declare a <layout> tag, which will wrap your existing layout file at the root level. Declare variables under the <data> tag, which will go under the <layout> tag. Declare necessary expressions to bind data inside the view elements.

What's data binding in Android?

The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.


1 Answers

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

Methods I needed were:

setTag() and getTag()

http://developer.android.com/reference/android/view/View.html#setTag%28java.lang.Object%29

like image 119
Leonti Avatar answered Sep 17 '22 18:09

Leonti