-2

I've created a method which adds a number of TextViews to a LinearLayout in a while loop. I'm having trouble identifying those TextViews by click. If I click on them, it prints out that they are the ID of my linear layout. Is there any way I can access them?

while(i.hasNext()){ 
        TextView x = new TextView(this);
        linearLayout.addView(x);
}

EDIT: I understand this was an absurdly dumb question. This...

x.setOnClickListener(this);

...did the trick.

drewvy22
  • 165
  • 1
  • 1
  • 10
  • Possible duplicate of [How can I assign an ID to a view programmatically?](http://stackoverflow.com/questions/8460680/how-can-i-assign-an-id-to-a-view-programmatically) – Charuක Mar 13 '17 at 04:45
  • @Charuක That does't work for my circumstance. – drewvy22 Mar 13 '17 at 04:52

2 Answers2

1

Simple, you will get the reference of clicked view in OnClickListener() callback. type cast that view into textview and call getText() method of textview. Here is sample code:

while(i.hasNext()) { 
  TextView x = new TextView(this);       
  linearLayout.addView(x);
    x.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
                TextView tv = (TextView) v;
                v.getText();
            }

    });
}
Vasily Kabunov
  • 5,179
  • 12
  • 41
  • 46
Ankit Saini
  • 357
  • 5
  • 14
0

if you'd be using a for loop you could do something like this x.setId(i+30); any number in place of 30. In while you can still take a variable i and do something like x.setId(x++ +30); . now if you want to access them from a loop its simple findViewById(i+30); or else findViewById(31);

AwaisMajeed
  • 1,647
  • 1
  • 8
  • 21