Checking for identifier in resources (R.id.something)

So, I have a code that generates an identifier for several elements using AtomicInteger, which is set by default to Integer.MAX_VALUE and decreases from there with each view that is assigned an identifier. Thus, the first view with the generated identifier will be Integer.MAX_VALUE - 1 , the second will be Integer.MAX_VALUE - 2 , etc. The problem I'm afraid of is a collision with identifiers generated by Android in R.java.

So my question is how to determine if an identifier is being used, and skip it when I create the identifiers. I generate no more than 30 identifiers, so this is not a huge priority. I would like to make it as white as possible.

+6
source share
4 answers

The following code will tell you if the identifier is an identifier or not.

 static final String PACKAGE_ID = "com.your.package.here:id/" ... ... int id = <your random id here> String name = getResources().getResourceName(id); if (name == null || !name.startsWith(PACKAGE_ID)) { // id is not an id used by a layout element. } 
+9
source

I changed the Jens answer above, because, as pointed out in the comments, the name will never be null, and an exception will be thrown instead.

 private boolean isResourceIdInPackage(String packageName, int resId){ if(packageName == null || resId == 0){ return false; } Resources res = null; if(packageName.equals(getPackageName())){ res = getResources(); }else{ try{ res = getPackageManager().getResourcesForApplication(packageName); }catch(PackageManager.NameNotFoundException e){ Log.w(TAG, packageName + "does not contain " + resId + " ... " + e.getMessage()); } } if(res == null){ return false; } return isResourceIdInResources(res, resId); } private boolean isResourceIdInResources(Resources res, int resId){ try{ getResources().getResourceName(resId); //Didn't catch so id is in res return true; }catch (Resources.NotFoundException e){ return false; } } 
+3
source

You can use the Java Reflection API to access which elements are present in the R.id Class object.

The code is as follows:

 Class<R.id> c = R.id.class; R.id object = new R.id(); Field[] fields = c.getDeclaredFields(); // Iterate through whatever fields R.id has for (Field field : fields) { field.setAccessible(true); // I am just printing field name and value, you can place your checks here System.out.println("Value of " + field.getName() + " : " + field.get(object)); } 
+1
source

Just an idea ... you can use findViewById (int id) to check if id .

0
source

Source: https://habr.com/ru/post/914448/


All Articles