<EditText
android:id="@+id/edit_text"
android:maxLength="500" //maxLength其实对应java里的LengthFilter,解决方法与这个InputFilter无关。
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
editText = findViewById(R.id.edit_text);
editText.setFilters(new InputFilter[]{editText.getFilters()[0], mInputFilter}); //这里的editText.getFilters()[0]是为了保留上面的xml设置的LengthFilter同时有效
InputFilter mInputFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
return source.toString().replace("\n", "");
}
};