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

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

    public String TAG() {
        return this.getClass().getSimpleName();
    }
    
    private AtomicInteger lastFldId = null;
    
    public int generateViewId(){
    
        if(lastFldId == null) {
            int maxFld = 0;
            String fldName = "";
            Field[] flds = R.id.class.getDeclaredFields();
            R.id inst = new R.id();
    
            for (int i = 0; i < flds.length; i++) {
                Field fld = flds[i];
    
                try {
                    int value = fld.getInt(inst);
    
                    if (value > maxFld) {
                        maxFld = value;
                        fldName = fld.getName();
                    }
                } catch (IllegalAccessException e) {
                    Log.e(TAG(), "error getting value for \'"+ fld.getName() + "\' " + e.toString());
                }
            }
            Log.d(TAG(), "maxId="+maxFld +"  name="+fldName);
            lastFldId = new AtomicInteger(maxFld);
        }
    
        return lastFldId.addAndGet(1);
    }
    

提交回复
热议问题