Search code examples
javaandroidtextviewonclicklisteneridentify

Identify dynamically added views for OnclickListener


I have a problem programming for Android:

I am adding textviews to a layout dynamically by reading out data out of an ArrayList. So I got different textviews on my layout. Now I want to set an OnclickListener to each of them and start different activities with an OnclickListener depending on which textview is clicked. But my problem is that I don't know how to identify the textviews. I add them like:

while(i<list.size()) {
    String name = list.get(i).getName();
    TextView txtViewName = new TextView(this);
    txtViewName.setText(name);
    layout.add(txtViewName);
    i++;
}

Everything works, but how can I set an OnclickListener for each txtView and how to identify them?

Thanks for you help!


Solution

  • The easiest way is to set the OnClickListener as an anonymous inner class inside the loop, and get it to do whatever's appropriate for that view:

    final int viewNum = i;
    txtViewName.setOnClickListener(new OnClickListener() {   
         @Override
         public void onClick(View view) {
             Toast.makeText(MainActivity.this, "You clicked on view "+viewNum, Toast.LENGTH_SHORT).show();
         }
    });
    

    This is just an example, but it shows how to get the listener to act differently for each view. It means you don't need anything else to identify your views, because you can use whatever you need inside the loop when you're setting the listener.

    A couple of things to note:

    1. I've assumed the enclosing activity is called MainActivity, but of course you'll need to change this to suit your case.
    2. Anonymous inner classes can only access final local variables. This is why I've set a final int viewNum = i, and then used that instead of i. It will have the same effect that you would naturally expect if you were allowed to use i. You'd need a similar trick if you wanted to refer to other local variables inside the onClick() method.