Android獲取文本框的光標位置,並在其位置中添加或刪除字符
public class TestActivity extends Activity{
private EditText phoneText;
private boolean phoneTextCursor = false;
private Button backBut,num1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
num1 = (Button)findViewById(R.id.num_1);
backBut = (Button)this.findViewById(R.id.backBut);
phoneText = (EditText) findViewById(R.id.phoneNum);
phoneText.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if(phoneText.getText().toString().trim().length()>0){
//設置光標為可見狀態
phoneText.setCursorVisible(true);
phoneTextCursor = true;
}
}});
num1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
downKey("1");
}
});
backBut.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer(phoneText.getText().toString().trim());
int index = 0;
if(phoneTextCursor==true)
{
index = phoneText.getSelectionStart();
if(index>0){
sb = sb.delete(index-1, index);
}
}
else{
index = phoneText.length();
if(index>0){
sb = sb.delete(index-1, index);
}
}
phoneText.setText(sb.toString());
if(index>0){
Selection.setSelection(phoneText.getText(), index-1);
}
if(phoneText.getText().toString().trim().length()<=0)
{
phoneText.setCursorVisible(false);
phoneTextCursor = false;
}
}});
}
//按鈕事件觸發手動調用此方法
public void downKey(String key)
{
//設置一個變量判斷是否有光標
if(phoneTextCursor==true)
{
//獲得光標的位置
int index = phoneText.getSelectionStart();
//將字符串轉換為StringBuffer
StringBuffer sb = new StringBuffer(phoneText.getText().toString().trim());
//將字符插入光標所在的位置
sb = sb.insert(index, key);
phoneText.setText(sb.toString());
//設置光標的位置保持不變
Selection.setSelection(phoneText.getText(), index+1);
}
else
{
phoneText.setText(phoneText.getText().toString().trim() + key);
}
//手機振動
toVibrate();
}
}
