Android--Android教程]EditText設置/隱藏光標位置、選中文本和獲取/清除焦點


[Android教程]EditText設置/隱藏光標位置、選中文本和獲取/清除焦點

有時候需要讓光標顯示在EditText的指定位置或者選中某些文本。同樣,為了方便用戶輸入以提升用戶體驗,可能需要使EditText獲得或失去焦點。 1. 設置光標到指定位置

  1. EditText et =(EditText) findViewById(R.id.etTest);
  2. et.setSelection(2);

PS:當內容過多時,可通過設置光標位置來讓該位置的內容顯示在屏幕上。 2. 隱藏光標

  1. EditText et =(EditText) findViewById(R.id.etTest);
  2. //設置光標不顯示,但不能設置光標顏色
  3. et.setCursorVisible(false);

3. 獲得焦點時全選文本

  1. EditText et =(EditText) findViewById(R.id.etTest);
  2. et.setSelectAllOnFocus(true);

PS:此方法可用來在用戶點擊EditText時,選中默認內容。 4. 獲取和失去焦點

  1. EditText et =(EditText) findViewById(R.id.etTest);
  2. et.requestFocus();//請求獲取焦點
  3. et.clearFocus();//清除焦點

5. 綜合運用代碼

  1. EditText et =(EditText) findViewById(R.id.etTest);
  2. int index = et.getSelectionStart();//獲取光標所在位置
  3. String text="#請在這里輸入話題#";
  4. Editable edit = et.getEditableText();//獲取EditText的文字
  5. if(index <0|| index >= edit.length()){
  6. edit.append(text);
  7. }else{
  8. edit.insert(index,text);//光標所在位置插入文字
  9. }
  10. et.setSelection(index +1, index + text.length()-1);

PS:在光標處插入文本,並選中##里面的文本

整理改編自: http://orgcent.com/android-edittext-cursor-position-focus/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM