我正在尝试测试动态生成的Spinner。我能够点击微调器然后我需要从列表中选择一个显示给定文本的选项(我从hierarchyviewer中发现PopupWindow显示但是无法获得所需的文本,这是在屏幕外) 。微调器使用自定义对象的ArrayAdapter(下面的代码),
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner mySpinner = (Spinner) findViewById(R.id.my_spinner);
List<MyValue> list = Arrays.asList(
new MyValue("One", "1"),
new MyValue("Two", "2"),
new MyValue("Three", "3"),
new MyValue("Four", "4"),
new MyValue("Five", "5"),
new MyValue("Six", "6"),
new MyValue("Seven", "7"),
new MyValue("Eight", "8"),
new MyValue("Nine", "9"),
new MyValue("Ten", "10"),
new MyValue("Eleven", "11"),
new MyValue("Twelve", "12"),
new MyValue("Thirteen", "13"),
new MyValue("Fourteen", "14"),
new MyValue("Fifteen", "15"),
new MyValue("Sixteen", "16"),
new MyValue("Seventeen", "17"),
new MyValue("Eighteen", "18"),
new MyValue("Nineteen", "19"),
new MyValue("Twenty", "20"),
new MyValue("Twenty One", "21")
);
final ArrayAdapter<MyValue> adapter = new ArrayAdapter<>(this,
R.layout.dropdown_selected_item,
list);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("MySpinnerTest", "current = " + adapter.getItem(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
}
public class MyValue {
String name;
String code;
public MyValue(String name, String code) {
this.name = name;
this.code = code;
}
@Override
public String toString() {
return name;
}
}
}
我尝试使用onData(withSpinnerText("Twenty")).perform(click())
但是获得了一个PerformException,我试图找出如何根据给定文本匹配正确的视图,在微调器弹出窗口中,但无法弄清楚如何执行此操作。
非常感谢任何帮助。
TIA
答案 0 :(得分:4)
找到一种方法来做到这一点,然后将答案发布到我自己的问题上。
我必须为我的对象创建一个自定义匹配器,然后将其与onData()
public static Matcher<Object> withMyValue(final String expectedName) {
return new BoundedMatcher<Object, MyValue>(MyValue.class) {
@Override
public void describeTo(Description description) {
description.appendText("with expectedName: " + expectedName);
}
@Override
protected boolean matchesSafely(MyValue myValue) {
return myValue.getName().equalsIgnoreCase(expectedName);
}
};
}
然后可以用作(在点击微调器后显示下拉列表)
onData(withMyValue(field.name)).perform(click());
答案 1 :(得分:0)
在mySpinner.setAdapter(adapter);
请添加以下这一行:
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);