雖然這兩個功能都比較簡單,但是在實際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()));
}
});
運行效果:

