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

來源:互聯網
上載者:User

標籤:android   http   io   os   ar   sp   div   art   on   

 

有時候需要讓游標顯示在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/

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.