我正在尝试在按下edittext上的回车键时简单地向列表视图添加内容。我还在一个按钮上有一个onclick监听器,它将调用相同的函数将该单词添加到listview。按钮工作正常,直到我添加了textwatcher。现在,如果我正在调用的函数在监听器中,如果我按Enter键或按下按钮,整个应用程序崩溃。如果我从textwatcher中删除该类,那么如果我按下Enter键,应用程序不会崩溃,但如果我按下按钮,它就会崩溃。有任何想法吗?我没有永远做过android,所以我完全卡住了。
XML
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/myEditText"
android:hint="Enter a new item"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="@+id/myDoneButton"
android:layout_toStartOf="@+id/myDoneButton"
android:layout_above="@+id/myListView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Item"
android:id="@+id/myDoneButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="onAddItem"
/>
JAVA
//On enter listener for mEditText (within oncreate)
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.charAt(s.length() - 1) == '\n') {
onAddItem(mListView);
Log.d("TEST RESPONSE", "Enter was pressed");
}
}
});
//Outside of oncreate
public void onAddItem(View v) {
String itemText = mEditText.getText().toString();
itemsAdapter.add(itemText);
mEditText.setText("");
writeItems();
}
以下是Logcat的相关信息
04-11 16:26:23.619 13377-13377/com.ivieinc.groceryapp E/AndroidRuntime:
FATAL EXCEPTION: main Process: com.ivieinc.groceryapp, PID: 13377 java.lang.IllegalStateException: Could not execute method for android:onClick
... (removed for clarity)
Caused by: java.lang.reflect.InvocationTargetException
... (removed for clarity)
Caused by: java.lang.IndexOutOfBoundsException: charAt: -1 < 0
at android.text.SpannableStringBuilder.charAt(SpannableStringBuilder.java:117)
at com.ivieinc.groceryapp.MainActivity$1.afterTextChanged(MainActivity.java:69)
at android.widget.TextView.sendAfterTextChanged(TextView.java:8007)
at android.widget.TextView.setText(TextView.java:4351)
at android.widget.TextView.setText(TextView.java:4199)
at android.widget.EditText.setText(EditText.java:84)
at android.widget.TextView.setText(TextView.java:4174)
at com.ivieinc.groceryapp.MainActivity.onAddItem(MainActivity.java:108)
... (removed for clarity)
答案 0 :(得分:0)
您的错误在这里:
if (s.charAt(s.length() - 1) == '\n') {
由于s为空,s.length
为零,并且您试图在索引-1处获取char ...
您必须验证可修改的