我的代码是:
EditText edt
edt.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
final String number = edt.getText().toString();
int count = arg0.length();
edt.setSelection(count);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
final String number = edt.getText().toString();
}
我也有拨号盘。当我点击拨号盘中的特定号码时,我需要将该号码添加到当前光标位置。此外,当我按删除时,我需要从当前光标位置删除该数字。
拨号盘图片
答案 0 :(得分:25)
尝试以下代码
int start =editText.getSelectionStart(); //this is to get the the cursor position
String s = "Some string";
editText.getText().insert(start, s); //this will get the text and insert the String s into the current position
以下是从EditText中删除所选文本的代码
int start = t1.getSelectionStart(); //getting cursor starting position
int end = t1.getSelectionEnd(); //getting cursor ending position
String selectedStr = t1.getText().toString().substring(start, end); //getting the selected Text
t1.setText(t1.getText().toString().replace(selectedStr, "")); //replacing the selected text with empty String and setting it to EditText
答案 1 :(得分:1)
您需要为按钮实施OnClickListener
。在那里你需要更新编辑器的文本。例如,对于'5'按钮:
public void onClick(View v) {
String currentText = edt.getText();
edt.setText(currentText + "5");
}
答案 2 :(得分:1)
要插入:
String dialled_nos = dialpad_text.getText().toString();
String number = view.getTag().toString(); // 1,2....9,0
int start = dialpad_text.getSelectionStart();
dialled_nos = new StringBuilder(dialled_nos).insert(start, number).toString();
dialpad_text.setText(dialled_nos);
dialpad_text.setSelection(start+1); // cursor will move to new position
删除:
String dialled_nos = dialpad_text.getText().toString();
int remove_index_position = dialpad_text.getSelectionStart()-1;
StringBuilder dialled_nos_builder = new StringBuilder(dialled_nos);
if(remove_index_position>=0) {
dialled_nos_builder.deleteCharAt(remove_index_position);
dialpad_text.setText(dialled_nos_builder.toString());
dialpad_text.setSelection(remove_index_position);
}
答案 3 :(得分:1)
etPnr.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) {
etPnr.removeTextChangedListener(this);
// TODO: If you want to do on the text, apply here
if (start + count > etPnr.length())
etPnr.setSelection(etPnr.length());
else
etPnr.setSelection(start + count);
etPnr.addTextChangedListener(this);
}
@Override
public void afterTextChanged(Editable s) {
}
});
你可以尝试一下
答案 4 :(得分:0)
editText.getText().insert(editText.getSelectionStart(), text);
text是您要插入的实际字符串。
答案 5 :(得分:0)
我目前使用此解决方案:
h function_name