Generally, IDs are automatically generated by Android. You only need to use R. id. xx for use. However, when developing Android jointly, You need to pack the self-developed code into a jar package, or even confuse it.
This requires the reflection mechanism of java. The following classes are used to retrieve IDs, avoiding hard encoding. Res files can only be handed over to partners. Of course there may be better solutions to this problem.
The usage is as follows:
(ImageButton) findViewById (GetItemId. getIdResIDByName (this, "title_exit "));
Import java. lang. reflect. Field;
Import android. content. Context;
Import android. util. Log;
Public class GetItemId {
Public static int getItemId (Context paramContext, String paramString1,
String paramString2 ){
Try {
Class LocalClass = Class. forName (paramContext. getPackageName ()
+ ". R$" + paramString1 );
Field localField = localClass. getField (paramString2 );
Int I = Integer. parseInt (localField. get (localField. getName ())
. ToString ());
Return I;
} Catch (Exception localException ){
Log. e ("getIdByReflection error", localException. getMessage ());
}
Return 0;
}
Public static int [] getItemIdArray (Context paramContext,
String paramString1, String paramString2 ){
Try {
Class LocalClass = Class. forName (paramContext. getPackageName ()
+ ". R$" + paramString1 );
Field localField = localClass. getField (paramString2 );
Int [] I = (int []) localField. get (localField. getName (). toString ());
Return I;
} Catch (Exception localException ){
Log. e ("getIdByReflection error", localException. getMessage ());
}
Return null;
}
Public static int getLayoutResIDByName (Context context, String name ){
Return context. getResources (). getIdentifier (name, "layout ",
Context. getPackageName ());
}
Public static int getIdResIDByName (Context context, String name ){
Return context. getResources (). getIdentifier (name, "id ",
Context. getPackageName ());
}
Public static int getStringResIDByName (Context context, String name ){
Return context. getResources (). getIdentifier (name, "string ",
Context. getPackageName ());
}
Public static int getDrawableResIDByName (Context context, String name ){
Return context. getResources (). getIdentifier (name, "drawable ",
Context. getPackageName ());
}
}