Android获取EditText光标位置进行增删操作


                                                 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();
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM