【发布时间】:2013-08-01 12:36:20
【问题描述】:
我在TextWatcher 的onTextChanged() 方法中得到EditText 的文本及其长度。
当我键入以添加字符时,它工作正常,但是从文本中删除字符时 getText() 即使文本不为空,也会给出空值。这会随机发生,而不是每次我删除字符时都会发生。我观察到这主要发生在文本中有 3-4 个字符并且我按退格键时。
奇怪的是这个问题只发生在设备上,而不是模拟器上。
布局文件:
<LinearLayout
style="@style/create_trip_activity_components_style"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_vertical"
android:orientation="horizontal" >
<EditText
android:id="@+id/from_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:ems="10"
android:hint="@string/from_location_hint"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="@+id/use_current_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:onClick="useCurrentLocation"
android:text="@string/use_current"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
代码:
fromLocation.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (fromLocation == null) {
Log.d(TAG, "fromLocation is null................");
}
Log.d(TAG, "fromLocation text : "
+ fromLocation.getText().toString());
Log.d(TAG, "fromLocation text length : "
+ fromLocation.getText().length());
Log.d(TAG, "S : "
+ s);
Log.d(TAG, "S length : "
+ s.length());
}
});
注意:我尝试使用afterTextChanged() 和beforeTextChanged() 方法。但这并没有解决问题。
【问题讨论】:
-
Editable 是一个 CharSequence,因此无需将其转换为 String 来调用 length()。只是在说。尝试在TextChanged(Editable s)之后注销。
-
@DoctororDrive 在
afterTextChanged()中尝试过。还是一样的问题。 -
可以显示你如何删除字符?
-
@Sameer 使用软键盘的键。
-
@Akash 请在下面查看我的答案,如果对您没有帮助,请告诉我。
标签: android null android-edittext gettext