如何将string(R.id.btn_0)转成int类型 - Espresso
How to convert string(R.id.btn_0) into int type - Espresso
我想将字符串类型转换成整型。我正在使用浓缩咖啡进行自动化操作。
根据点击对象的 espresso 自动化语法,onView(withid(R.id.btn_0).perform(click())
我有 json 文件,我在其中存储了对象,
"btn_0": {
"ANDROID": "withId=R.id.btn_0"
}
现在,当我读取 btn_0 时,我得到 btn_0 对象的字符串值并且 withId() 接受 int。
注意:Integer.parseInt() 将不起作用。
谁能帮我解决这个问题?
下面是解决方法,试试这个
while( i < withId.length()) {
num *= 10;
num += withId.charAt(i++) - '0';
}
此处提供此变通方法,请查看:How do I convert a String to an int in Java?
您可以使用Resources.getIdentifier()
方法将资源名称解析为整数,我为您准备了一个示例:
@Test
public void parseResourceIdTest() {
final Context context = InstrumentationRegistry.getTargetContext();
assertEquals(R.id.btn_0, parseResourceId(context, "btn_0"));
}
public static int parseResourceId(@NonNull Context context, @NonNull String string) {
return context.getResources().getIdentifier(string, "id", context.getPackageName());
}
而不是像 "R.id.modeName" 那样传递整个 ID 只传递 "modeName"
最终上下文上下文=InstrumentationRegistry.getTargetContext();
int obj = context.getResources().getIdentifier("modeName", "id", context.getPackageName());
onView(withId(obj)).perform(click());
我想将字符串类型转换成整型。我正在使用浓缩咖啡进行自动化操作。
根据点击对象的 espresso 自动化语法,onView(withid(R.id.btn_0).perform(click())
我有 json 文件,我在其中存储了对象,
"btn_0": {
"ANDROID": "withId=R.id.btn_0"
}
现在,当我读取 btn_0 时,我得到 btn_0 对象的字符串值并且 withId() 接受 int。
注意:Integer.parseInt() 将不起作用。
谁能帮我解决这个问题?
下面是解决方法,试试这个
while( i < withId.length()) {
num *= 10;
num += withId.charAt(i++) - '0';
}
此处提供此变通方法,请查看:How do I convert a String to an int in Java?
您可以使用Resources.getIdentifier()
方法将资源名称解析为整数,我为您准备了一个示例:
@Test
public void parseResourceIdTest() {
final Context context = InstrumentationRegistry.getTargetContext();
assertEquals(R.id.btn_0, parseResourceId(context, "btn_0"));
}
public static int parseResourceId(@NonNull Context context, @NonNull String string) {
return context.getResources().getIdentifier(string, "id", context.getPackageName());
}
而不是像 "R.id.modeName" 那样传递整个 ID 只传递 "modeName"
最终上下文上下文=InstrumentationRegistry.getTargetContext(); int obj = context.getResources().getIdentifier("modeName", "id", context.getPackageName()); onView(withId(obj)).perform(click());