I had a similar problem when I reused the button layout and it gave me some matches in a hierarchy exception.
So the easy work around me was to create two different screens and two different methods with different text.
Cancel screen:
public WithdrawScreen clickWithdraw() { onView(allOf(withId(R.id.save_button), withText("Withdraw"))) .perform(click()); return this; }
Deposit Screen:
public DepositScreen clickDeposit() { onView(allOf(withId(R.id.save_button), withText("Deposit"))) .perform(click()); return this; }
and in my tests, I create a new instance of both screens and call the above methods based on the screen link, which is a little easy to verify.
WithdrawScreen withdrawInstance = new WithdrawScreen(); withdrawInstance.clickWithdraw(); DepositScreen depositInstance = new DepositScreen(); depositInstance.clickDeposit();
The bottom line is that they used the same identifier - R.id.save_button for the button, and I changed the button text based on the visibility of the fragment in which we are.
Hope this helps.
source share