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

前端 未结 15 2803
眼角桃花
眼角桃花 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:23

    int fID;
    do {
        fID = Tools.generateViewId();
    } while (findViewById(fID) != null);
    view.setId(fID);
    

    ...

    public class Tools {
        private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
        public static int generateViewId() {
            if (Build.VERSION.SDK_INT < 17) {
                for (;;) {
                    final int result = sNextGeneratedId.get();
                    int newValue = result + 1;
                    if (newValue > 0x00FFFFFF)
                        newValue = 1; // Roll over to 1, not 0.
                    if (sNextGeneratedId.compareAndSet(result, newValue)) {
                        return result;
                    }
                }
            } else {
                return View.generateViewId();
            }
        }
    }
    

提交回复
热议问题