Android获取动态添加控件的Id

最近在写自定义view。需要动态的添加到布局中、找到一份这个记录一下!!!

IdUtils.Java(常用在sdk里面)

[java]  view plain  copy
 
  1. /** 
  2.  * id 
  3.  * 兼容sdk17(4.2.2)以下 
  4.  * Created by zst on 2016/12/5. 
  5.  */  
  6. public class IdiUtils {  
  7.   
  8.     private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);  
  9.     public static int generateViewId() {  
  10.         for (;;) {  
  11.             final int result = sNextGeneratedId.get();  
  12.             // aapt-generated IDs have the high byte nonzero; clamp to the range under that.  
  13.             int newValue = result + 1;  
  14.             if (newValue > 0x00FFFFFF) newValue = 1// Roll over to 1, not 0.  
  15.             if (sNextGeneratedId.compareAndSet(result, newValue)) {  
  16.                 return result;  
  17.             }  
  18.         }  
  19.     }  
  20. }  

调用

[java]  view plain  copy
 
  1. tv_leftBtn_title.setId(IdiUtils.generateViewId());  

你可能感兴趣的:(Android中级)