有時(shí)候需要讓光標(biāo)顯示在EditText的指定位置或者選中某些文本蔑舞。同樣,為了方便用戶輸入以提升用戶體驗(yàn)嘹屯,可能需要使EditText獲得或失去焦點(diǎn)攻询。
- 設(shè)置光標(biāo)到指定位置
EditText et = (EditText) findViewById(R.id.etTest);et.setSelection(2);
PS:當(dāng)內(nèi)容過多時(shí),可通過設(shè)置光標(biāo)位置來讓該位置的內(nèi)容顯示在屏幕上州弟。
- 隱藏光標(biāo)
EditText et = (EditText) findViewById(R.id.etTest);//設(shè)置光標(biāo)不顯示,但不能設(shè)置光標(biāo)顏色et.setCursorVisible(false);
- 獲得焦點(diǎn)時(shí)全選文本
EditText et = (EditText) findViewById(R.id.etTest);et.setSelectAllOnFocus(true);
PS:此方法可用來在用戶點(diǎn)擊EditText時(shí)钧栖,選中默認(rèn)內(nèi)容。
- 獲取和失去焦點(diǎn)
EditText et = (EditText) findViewById(R.id.etTest);et.requestFocus(); //請求獲取焦點(diǎn)et.clearFocus(); //清除焦點(diǎn)