【问题标题】:Clearing the entire text before cursor position on EditText在EditText上的光标位置之前清除整个文本
【发布时间】:2012-02-13 02:36:18
【问题描述】:

我想清除光标位置之前的 EditText 上的整个文本。假设我的文本是 1234567890光标在字符 4 之后像这样 1234|567890 现在我的要求是我有一个自定义按钮,删除光标位置之前的文本。

我正在使用editext.getText().clear(); 来清除文本,但它会清除整个文本。如果光标在文本的末尾,那很好。

是否有可能达到我的要求?如果是怎么办?请帮我解决这个问题。

【问题讨论】:

    标签: android android-edittext


    【解决方案1】:

    以下是处理方法:

    您将使用以下方法获得光标位置:

    editText.getSelectionStart();
    

    editText.getSelectionEnd();
    

    注意:如果没有选择文本,两种方法都将返回相同的索引。

    然后将文本 EditText 和 然后再次设置为EditText。像这样:

    int pos = editText.getSelectionStart();
    String myText = editText.getText().toString();
    //sub-string it.
    String subStringed = myText.substring(pos, myText.length());
    //set it again..
    editText.setText(subStringed);
    

    【讨论】:

    • 感谢您的回答。它的工作,但最后我必须使用 subStringed 而不是 myText.
    【解决方案2】:

    以下答案可能会对您有所帮助。它非常适合我

    EditText光标的选定位置插入文本/字符

    int start = edtPhoneNo.getSelectionStart(); //this is to get the cursor position
        String s="sagar";//s="0123456789";
        edtPhoneNo.getText().insert(start, s);
        //this is to set the cursor position by +1 after inserting char/text
        edtPhoneNo.setSelection(start + 1);
    

    删除EditText光标选定位置的文本/字符

     int curPostion = edtPhoneNo.getSelectionEnd();   
         SpannableStringBuilder selectedStr = new 
         SpannableStringBuilder(edtPhoneNo.getText());
         selectedStr.replace(curPostion - 1, curPostion, "");
         edtPhoneNo.setText(selectedStr);
         //this is to set the cursor position by -1 after deleting char/text
         edtPhoneNo.setSelection(curPostion - 1);
    

    EditText光标设置在最后一个位置

     edtPhoneNo.setSelection(edtPhoneNo.getText().length());
    

    这是EditText 的 XML 代码

    <EditText
                android:id="@+id/edtPhoneNumber"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@android:color/transparent"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:maxLines="1" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多