Android: View.setID(int id) programmatically - how to avoid ID conflicts?

前端 未结 15 2488
眼角桃花
眼角桃花 2020-11-21 22:53

I\'m adding TextViews programmatically in a for-loop and add them to an ArrayList.

How do I use TextView.setId(int id)? What Integer ID do I come up wit

15条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 23:41

    I use:

    public synchronized int generateViewId() {
        Random rand = new Random();
        int id;
        while (findViewById(id = rand.nextInt(Integer.MAX_VALUE) + 1) != null);
        return id;
    }
    

    By using a random number I always have a huge chance of getting the unique id in first attempt.

提交回复
热议问题