天天看点

Java设置edittext光标_将光标放在EditText中文本的末尾

我测试的所有其他代码都不能正常工作,因为用户仍然可以将插入符号/光标放在字符串中间的任何位置(例如:12 | 3.00 - 其中|是光标) . 只要在EditText上发生触摸,我的解决方案总是将光标放在字符串的末尾 .

最终的解决方案是:

// For a EditText like:

android:id="@+id/EditTextAmount"

android:layout_height="wrap_content"

android:layout_width="fill_parent"

android:hint="@string/amount"

android:layout_weight="1"

android:text="@string/zero_value"

android:inputType="text|numberDecimal"

android:maxLength="13"/>

@ string / amount =“0.00”@ string / zero_value =“0.00”

// Create a Static boolean flag

private static boolean returnNext;

// Set caret/cursor to the end on focus change

EditTextAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {

@Override

public void onFocusChange(View editText, boolean hasFocus) {

if(hasFocus){

((EditText) editText).setSelection(((EditText) editText).getText().length());

}

}

});

// Create a touch listener and put caret to the end (no matter where the user touched in the middle of the string)

EditTextAmount.setOnTouchListener(new View.OnTouchListener() {

@Override

public boolean onTouch(View editText, MotionEvent event) {

((EditText) editText).onTouchEvent(event);

((EditText) editText).setSelection(((EditText) editText).getText().length());

return true;

}

});

// Implement a Currency Mask with addTextChangedListener

EditTextAmount.addTextChangedListener(new TextWatcher() {

@Override

public void onTextChanged(CharSequence s, int start, int before, int count) {

String input = s.toString();

String output = new String();

String buffer = new String();

String decimals = new String();

String numbers = Integer.toString(Integer.parseInt(input.replaceAll("[^0-9]", "")));

if(returnNext){

returnNext = false;

return;

}

returnNext = true;

if (numbers.equals("0")){

output += "0.00";

}

else if (numbers.length() <= 2){

output += "0." + String.format("%02d", Integer.parseInt(numbers));

}

else if(numbers.length() >= 3){

decimals = numbers.substring(numbers.length() - 2);

int commaCounter = 0;

for(int i=numbers.length()-3; i>=0; i--){

if(commaCounter == 3){

buffer += ",";

commaCounter = 0;

}

buffer += numbers.charAt(i);

commaCounter++;

}

output = new StringBuilder(buffer).reverse().toString() + "." + decimals;

}

EditTextAmount.setText(output);

EditTextAmount.setSelection(EditTextAmount.getText().length());

}

@Override

public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override

public void afterTextChanged(Editable s) {

}

});

希望能帮助到你!