I am putting together a small android library to be used by other developers in their android apps. The 3rd party developer will add my custom button e.g."com.example.myLibrary.CustomButton" into their xml views. The developer can put as many of these buttons in as required.
Is there a way for my library code to identify how many of these custom buttons are in the activity and then return their ID's which could be anything set by the app developer?
I have experimented with int[] i = getResources().getIdentifier("name","component","package");
but it returns a 6 digit int which i assume is some system identifier for the component and not each instance of it.
NOTE -- I am aware that the library will need context of the app activity via something like new MyLibrary(context);
to pass the context of the app activity. I have this implemented for other aspects of the library so that would not appear to be an issue.
Many thanks in advance of any suggestions that can help with the issue
IDs in Android are integers that are automatically assigned at runtime unless previously declared. The IDs are unique to each control, but the @+id/myIdName
piece is just for referencing in code (think enumeration). These resource IDs can be referenced by name by using:
getResources().getResourceEntryName(int resid);
A couple other options if you need to get all the resource IDs at once.
1) Wrap the class into a manager of sorts that tracks the information for you.
2) Iterate through all components in the activity
//make an array list to hold the info
ArrayList<MyView> ids = new ArrayList<>();
//get the window to look through
ViewGroup viewGroup = (ViewGroup) getWindow().getDecorView();
//call things recursively
findAllViews(viewGroup, ids);
private static void findAllViews(ViewGroup viewGroup,ArrayList<Integer> ids) {
for (int i = 0, n = viewGroup.getChildCount(); i < n; i++) {
View child = viewGroup.getChildAt(i);
if (child instanceof ViewGroup) {
findAllViews((ViewGroup) child, ids);
} else if (child instanceof Button) {
ids.add((Integer) child.getId());
}
}
}