Android EditText插入表情(字串)到游標位置

來源:互聯網
上載者:User

標籤:android   blog   io   ar   os   使用   sp   java   on   

前言    之前寫的一個Android應用,在回複文章插入表情的時候存在一個BUG,就是無法在EditText中指定的游標處插入表情字串,每次添加的表情字串都跑到了文字末尾。分析了一下apk源碼,發現是在表情盤的onClick響應事件中沒有正確處理表情字串的添加方法,這裡記錄一下如何在EditText指定游標處插入表情字串。
EditText游標處插入表情字串的方法    既然是在EditText控制項中插入表情字串,那首先需要擷取EditText控制項對象,樣本源碼如下:
EditText rEditText = (EditText) findViewById(R.id.r_edittext);
    擷取了當前EditText控制項對象,下一步是要儲存當前EditText中已有的字串,樣本源碼如下:
String oriContent = rEditText.getText().toString();
    接下來,就是要擷取游標的位置了。使用EditText控制項提供的getSelectionStart()方法。但是,這裡需要注意的是,當EditText中沒有游標時,使用該方法將返回-1,這顯然不是我們想要的游標位置,因此最好和0再做個比較,樣本源碼如下:
int index = Math.max(rEditText.getSelectionStart(), 0);
    剩下的,就是在給定的游標位置插入表情字串了,然後再設定新的游標位置。完整的插入表情樣本源碼如下:
private void insertEmotion(String insertEmotion) {String oriContent = rEditText.getText().toString();int index = Math.max(rEditText.getSelectionStart(), 0);StringBuilder sBuilder = new StringBuilder(oriContent);sBuilder.insert(index, insertEmotion);rEditText.setText(sBuilder.toString());rEditText.setSelection(index + insertEmotion.length());}

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.