Search code examples
javaandroidseleniumautomationappium

How to select a random element by its index?


Lets say I have five elements in an android app with their own respective index

driver.findElement(By.xpath("//android.widget.FrameLayout[@index='0']/android.widget.ImageView[@index='0']")).click();
driver.findElement(By.xpath("//android.widget.FrameLayout[@index='1']/android.widget.ImageView[@index='0']")).click();
driver.findElement(By.xpath("//android.widget.FrameLayout[@index='2']/android.widget.ImageView[@index='0']")).click();
driver.findElement(By.xpath("//android.widget.FrameLayout[@index='3']/android.widget.ImageView[@index='0']")).click();
driver.findElement(By.xpath("//android.widget.FrameLayout[@index='4']/android.widget.ImageView[@index='0']")).click();

And I only want to click one out of the five. What command would I use to make this possible?


Solution

  • Generate a random number between 0 and 4

    Random r = new Random();
    int result = r.nextInt(5);
    
    
    
    driver.findElement(By.xpath("//android.widget.FrameLayout[@index='"+result+"']/android.widget.ImageView[@index='0']")).click();