此代码尝试捕获 EditText 的字符串并将其与数组字符串进行比较。代码没有错误,但是当我点击按钮时没有任何反应(甚至没有显示吐司),我做错了什么?谢谢
这是数组数组。列表.xml
<resources>
<string-array name="array1">
<item name="number">1</item>
<item name="name">first</item>
</string-array>
<string-array name="array2">
<item name="number">2</item>
<item name="name">second</item>
</string-array>
<array name="list">
<item>@array/array1</item>
<item>@array/array2</item>
</array>
</resources>
这是主 xml 文件的代码主.xml
<EditText
android:id="@+id/etname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="text"
android:imeOptions="actionDone" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:onClick="searchArray"
android:text="@string/search" />
搜索数组
public void searchArray(View view){
Resources res = getResources();
TypedArray ta = res.obtainTypedArray(R.array.list);
int n = ta.length();
String[][] array = new String[n][];
for (int i = 0; i < n; ++i) {
int id = ta.getResourceId(i, 0);
if (id > 0) {
array[i] = res.getStringArray(id);
} else {
// something wrong with the XML
}
}
ta.recycle();
TextView name = (TextView) findViewById(R.id.etname);
String stringname = name.getText().toString();
if (stringname != null){
for (int cont = 0; cont < n; ++cont) {
if (!(array[cont][1].equals(stringname))){
Toast toast2 = Toast.makeText(getApplicationContext(), array[cont][1], Toast.LENGTH_SHORT);
toast2.show();
} else {
Toast toast = Toast.makeText(getApplicationContext(), "WRONG", Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
您似乎从索引 1 而不是 0 进行比较。更改代码
for (int cont = 0; cont < n; ++cont)
自
for (int cont = 0; cont < n; cont++)
试试这样,
public void searchArray(View view){
Resources res = getResources();
TypedArray ta = res.obtainTypedArray(R.array.list);
int n = ta.length();
String[][] array = new String[n][];
for (int i = 0; i < n; i++) {
int id = ta.getResourceId(i, 0);
if (id > 0) {
array[i] = res.getStringArray(id);
System.out.println(res.getStringArray(id));
} else {
// something wrong with the XML
}
}
ta.recycle();
EditText name = (EditText) findViewById(R.id.etname);// I changed TextView to EditText
String stringname = name.getText().toString();
if (stringname != null){
for (int cont = 0; cont < n; ++cont) {
System.out.println(array[cont][1]+" "+stringname);
if ((array[cont][1].equals(stringname))){//Edit Here, If it matches, Show Toast
Toast toast2 = Toast.makeText(getApplicationContext(), array[cont][1], Toast.LENGTH_SHORT);
toast2.show();
} else {
Toast toast = Toast.makeText(getApplicationContext(), "WRONG", Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
希望这对你有帮助。