溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在Android項(xiàng)目中利用EditText監(jiān)聽并顯示字?jǐn)?shù)

發(fā)布時(shí)間:2020-11-24 15:07:40 來源:億速云 閱讀:371 作者:Leah 欄目:移動(dòng)開發(fā)

如何在Android項(xiàng)目中利用EditText監(jiān)聽并顯示字?jǐn)?shù)?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。

在開發(fā)應(yīng)用的時(shí)候,經(jīng)常會(huì)限制用戶輸入的字?jǐn)?shù),比如發(fā)表評(píng)論或者其它什么的,下面來個(gè)簡(jiǎn)單的demo

EditText et_content;//定義一個(gè)文本輸入框
TextView tv_num;// 用來顯示剩余字?jǐn)?shù)
int num = 10;//限制的最大字?jǐn)?shù)
et_content = (EditText) findViewById(R.id.et_content);
tv_num = (TextView) findViewById(R.id.tv_num);
tv_num.setText("10");

下面為EditText文本框添加監(jiān)聽

et_content.addTextChangedListener(new TextWatcher() {
  private CharSequence temp;
  private int selectionStart;
  private int selectionEnd;
  @Override
  public void onTextChanged(CharSequence s, int start, int before,
      int count) {
    temp = s;
    System.out.println("s="+s);
  }
  @Override
  public void beforeTextChanged(CharSequence s, int start, int count,
      int after) {
  }
  @Override
  public void afterTextChanged(Editable s) {
    int number = num - s.length();
    tv_num.setText("" + number);
    selectionStart = et_content.getSelectionStart();
    selectionEnd = et_content.getSelectionEnd();
    //System.out.println("start="+selectionStart+",end="+selectionEnd);
    if (temp.length() > num) {
      s.delete(selectionStart - 1, selectionEnd);
      int tempSelection = selectionStart;
      et_content.setText(s);
      et_content.setSelection(tempSelection);//設(shè)置光標(biāo)在最后
    }
  }
});

關(guān)于如何在Android項(xiàng)目中利用EditText監(jiān)聽并顯示字?jǐn)?shù)問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI