android中實現在矩形框中輸入文字,可以顯示剩餘字數的功能,android字數

來源:互聯網
上載者:User

android中實現在矩形框中輸入文字,可以顯示剩餘字數的功能,android字數

雖然這兩個功能都比較簡單,但是在實際app開發中真的很常見,特別是顯示字數或剩餘字數這個功能

如:

 

要實現上面的功能,需要做到三點:

1、實現矩形框布局

思路就是矩形框作為整個布局的一個background,在drawable中建立一個shap.xml樣式檔案

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle" >    <padding        android:bottom="1dp"        android:left="1dp"        android:right="1dp"        android:top="1dp" />    <!-- 設定圓角矩形 -->    <!--<corners android:radius="3dp" />-->    <stroke        android:width="1px"        android:color="#000" />    <solid android:color="#ffff" /></shape>

在布局檔案中設定

android:background="@drawable/shap" 

然後將editText和Textview按照要求布局到該矩形地區中

 

2、隱藏editText的底線

預設情況下,editText中輸入文字後,下面都會有底線,可以使用

android:background="@null"

將其底線隱藏。

 

3、計算剩餘字數

這個問題可以通過對editText控制項調用addTextChangedListener()方法實現監聽

        final int maxNum = 500;              final TextView leftNum = (TextView) findViewById(R.id.leftNum);        EditText ed = (EditText) findViewById(R.id.nikeName);                ed.addTextChangedListener(new TextWatcher() {            @Override            public void beforeTextChanged(CharSequence s, int start, int count, int after) {            }            @Override            public void onTextChanged(CharSequence s, int start, int before, int count) {            }            @Override            public void afterTextChanged(Editable s) {                leftNum.setText("剩餘字數:"+ (maxNum-s.length()));            }        });           

運行效果:

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.