Еще несколько часов работы привели к созданию этого рабочего решения, но мне любопытно, есть ли у кого-нибудь еще лучшее решение.Этот код был вдохновлен этим решением на аналогичный вопрос, но этот случай отличается в двух отношениях:
- Он предназначен для использования Android JUnit, что означает, что ему нужно вызватьпользовательский интерфейс ListPreference щелкает по
runOnUiThread()
. - . Предполагается, что используются категории предпочтений, которые затрудняют поиск позиции (относительно всего списка предпочтений) для нажатия.Вышеупомянутое решение работает только в случаях без категорий предпочтений.
Этот метод примет ключ для определенного элемента ListPreference вместе с положением элемента в списке, по которому нужно щелкнуть.Затем он выполнит щелчок по этому элементу списка, а другой код выполнит проверку, которую я ищу.
Обратите внимание, что для этого необходимо установить setActivityInitialTouchMode(true);
перед вызовом getActivity()
в методе setUp()
.
private void clickListPreference(String _listPreferenceKey, int _listItemPos){
final String listPreferenceKey = _listPreferenceKey;
final int listItemPos = _listItemPos;
mActivity.runOnUiThread(
new Runnable() {
public void run() {
// get a handle to the particular ListPreference
ListPreference listPreference= (ListPreference) mActivity.findPreference(listPreferenceKey);
// bring up the dialog box
mActivity.getPreferenceScreen().onItemClick( null, null, getPreferencePosition(), 0 );
// click the requested item
AlertDialog listDialog = (AlertDialog) listPreference.getDialog();
ListView listView = listDialog.getListView();
listView.performItemClick(listView, listItemPos, 0);
}
/***
* Finding a ListPreference is difficult when Preference Categories are involved,
* as the category header itself counts as a position in the preferences screen
* list.
*
* This method iterates over the preference items inside preference categories
* to find the ListPreference that is wanted.
*
* @return The position of the ListPreference relative to the entire preferences screen list
*/
private int getPreferencePosition(){
int counter = 0;
PreferenceScreen screen = mActivity.getPreferenceScreen();
// loop over categories
for (int i = 0; i < screen.getPreferenceCount(); i++){
PreferenceCategory cat = (PreferenceCategory) screen.getPreference(i);
counter++;
// loop over category items
for (int j = 0; j < cat.getPreferenceCount(); j++){
if (cat.getPreference(j).getKey().contentEquals(listPreferenceKey)){
return counter;
}
counter++;
}
}
return 0; // did not match
}
}
);
getInstrumentation().waitForIdleSync();
}