UIAutomator中滾動ListView獲得目標TextView控制元件物件的經驗點滴
阿新 • • 發佈:2019-01-06
當建立一個UiScrollable物件時,如果指定的引數是new UiSelector().scrollable(true),那麼會出現以下問題
- 當可滾動控制元件(比如ListView)不滿一頁不需要滾動時,建立的UiSrollable物件返回值是為空的。
//Find out the new added note entry UiScrollable noteList = new UiScrollable( new UiSelector().scrollable(true)); //would be null if the scrollable widget's not more than one page UiObject note = null;
note = noteList.getChildByText(new UiSelector().className("android.widget.TextView"), "Note1", true);
<pre name="code" class="java"> assertThat(note,notNullValue());
note.longClick();
我們可以做一個增強,當判斷返回的UiScrollable物件是空的時候,我們直接去當前頁面查詢目標控制元件:
//Find out the new added note entry UiScrollable noteList = new UiScrollable( new UiSelector().scrollable(true)); UiObject note = null;
if(noteList.exists()) {
note = noteList.getChildByText(new UiSelector().className("android.widget.TextView"), "Note1", true);
}
else {
note = new UiObject(new UiSelector().text("Note1"));
}
assertThat(note,notNullValue());
note.longClick();
另外一個個人認為更好的解決辦法是,不要以“UiSelector().scrollable(true)”來初始化UiScrollable物件,而是明確的指定className為“android.widget.ListView"來初始化UiScrollable物件。實踐證明這樣子做的話就算ListView的內容很少不需要翻頁時,也能夠找到指定的當前頁面的目標控制元件//Find out the new added note entry
UiScrollable noteList = new UiScrollable( new UiSelector().className("android.widget.ListView"));
UiObject note = null;
note = noteList.getChildByText(new UiSelector().className("android.widget.TextView"), "Note1", true);
assertThat(note,notNullValue());
note.longClick();