问题
For example: I enter 1 in edittext then again if i type 2 in same edittext then not want to remove manualy 1 but want to override it directly from 1 to 2.
For Example:
editTextOtpFirst.addTextChangedListener(this);
editTextOtpSecond.addTextChangedListener(this);
@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 (editTextOtpFirst.getText().length() ==1 && !checkEditTextEmpty(editTextOtpFirst)) {
editTextOtpSecond.requestFocus();
}
if (editTextOtpSecond.getText().length() ==1 && !checkEditTextEmpty(editTextOtpFirst) ) {
editTextOtpThird.requestFocus();
}
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (v.getId() == R.id.editTextOtpThird) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
editTextOtpSecond.requestFocus();
return true;
}
}
}
if (v.getId() == R.id.editTextOtpFourth) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
editTextOtpThird.requestFocus();
return true;
}
}
}
if (v.getId() == R.id.editTextOtpSecond) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_DEL) {
editTextOtpFirst.requestFocus();
return true;
}
}
}
Now when i enter value "1" in edit text-1 then cursor move to the next edit text-2 but i want to change value of edit text-1 from "1" to "4" but need to remove manually "1" and then need to enter another value..but i do not want this...i want to direct override from "1" to "4" when i type another value in edit text.
回答1:
You can do this using a TextWatcher
by adding an onTextChangeListener
to the edit text, something like this:
editText.addOnTextChangeListener(new TextWatcher{
beforeTextChanged(..){
// ..... can try something here
}
onTextChanged(Charsequence text, ...){
// or can append the text to the editText here
editText.setText("");
editText.append(text);
}
});
Also i'm writing this code on the go so please look for proper syntaxing ps. the interface names are correct. Hope this help!
回答2:
I think your solution would be using the edit text hint instead of text. You can set the hint color to whatever color you want the text to be. Then you can use the setHint
method.
回答3:
You can add this single line to your layout xml file, and android will do the stuff for you
android:maxLength="1"
you should add it as a property to the editText element, for example
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLength="1" />
It's an old question, but I think this will work out fine.
来源:https://stackoverflow.com/questions/46170674/how-to-override-text-of-edit-text-when-maxlength-of-edittext-is-1