How to get Android element by id that is set programmatically

I’m trying to get an element by id and this id is set programmatically.

Example:
In my Android views I set an ID like this view.setId(R.id.myId) and on Appium I can’t find this element by this ID. This ID also doesn’t show in Appium Inspector Tool

Does this id shown in Android inspector? Guess no. Cause in android you cant set ids dynamically it should be some predefined resource. Anyway check with android inspector first that is in sdk tools.

Yes, it shows, but I don’t know how to reference it on Appium.

MobileElement el = driver.findElement(MobileBy.id="yourID");

// or pageObject annotation
@AndroidFindBy(id = "yourID")
private MobileElement el;

But this should be a resource id that exist on xml, right?

I am asking this because I have one scenario that I create views dynamically and the ID is dynamically generated as well.

if it visible in “uiautomatorviewer” appium will find it

UIAutomatorView does not recognize dynamic IDs nor programmatically IDs.

if you cant see them in UIAutomatorView you cant do anything. as workaround, when we need to set something dynamic, we use content description. Which is visible and we can find it:

el.getAttribute("content-desc")
// or
@AndroidFindBy(uiAutomator = "new UiSelector().description(\"your_description\")")
private MobileElement someLabel;
// or
MobileElement el = driver.findElement(MobileBy.AndroidUIAutomator("new UiSelector().description(\"your_description\")"));

Do you think is it possible to contribute to Appium and add support to programmatically IDs?

I am asking this because I don’t know how the development roadmap is done and this feature it’s super important to the project that I am working on.

If the attribute is not visible in the page source then there is probably no way to access it using automation framework because it is simply not exposed to the accessibility. Try your luck with Espresso

Espresso indeed has some means of retrieving the created id, but we are migrating to Appium because we test both Android and iOS in a single project. By the way, in iOS the ids created using ‘setId’ show in its inspector (accessibility-id \ name) and are accessible by Appium. So we have this Appium-Android behavior that is hindering our project. Like @tuliopereirazup said, do you think it’s possible to contribute somehow with Appium to enable retrieving such ids? Or is it a contribution to Android \ UIAutomator2 instead?

you need contribute to UIAutomator2 :slight_smile: which is not in Google priority after moving to Espresso

Yes, it would be rather a contribution to the Android Accessibility and/or UiAutomator framework. Regarding Espresso: Appium has a driver for it as well: https://github.com/appium/appium-espresso-driver