• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
lamber
博客园    首页    新随笔       管理    订阅  订阅

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

}

想要获得成功,首先要自己相信自己,再者要赢得周围朋友的信任!
posted @ 2012-07-05 15:30  android5k  阅读(4319)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3