Search code examples
androidtextviewfindviewbyid

How to find TextView with ID when creating ID's with View.GenerateViewId


I'm creating X amount of TextViews dynamically and giving them ID's with View.generateViewId().

 TextView textView = new TextView(this);
  textView.setText("_");
  ...
  ...  
  int id = View.generateViewId();
  textView.setId(id);

And I get some IDs generated e.g 1-5, depending on the number of TextViews. But after searching different forums and the official android site I can't figure out how to access these ID's.

How do I target lets say the TextView with ID = 1 if I want to setText() in that one? Tried some different things like using findViewById and R-class but doesn't seem to work.

Appreciate any direct help or links that are relevant, thanks.


Solution

    1. declare the map:

      public static final Map<String, Integer> ITEM_MAP = new HashMap<String, Integer>();
      
    2. keep a track of items:

      int id = View.generateViewId();
      textView.setId(id);
      ITEM_MAP.put("key1", id);
      
      int id2 = View.generateViewId();
      textView.setId(id2);
      ITEM_MAP.put("key2", id2);
      

    3.and then when needed:

        int id = ITEM_MAP.get("key?X"); 
        TextView textView = findViewById(id);
    

    Good luck )