先看效果图:
布局文件:activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="问题和意见"
android:textColor="#000000"
android:textSize="14sp" />
<TextView
android:id="@+id/tv_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0/500"
android:textColor="#000000"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dp_16"
android:layout_marginTop="@dimen/dp_8"
android:layout_marginEnd="@dimen/dp_16"
android:layout_marginBottom="@dimen/dp_47"
android:background="@drawable/bg_r16_ffffff"
android:orientation="vertical">
<EditText
android:id="@+id/et_questions_comments"
android:layout_width="wrap_content"
android:layout_height="@dimen/dp_150"
android:background="@null"
android:gravity="top"
android:hint="@string/str_questions_and_comments_hint"
android:padding="@dimen/dp_16"
android:textColor="@color/black"
android:textColorHint="@color/hint_text_color"
android:textSize="@dimen/sp_14"
tools:ignore="Autofill" />
</LinearLayout>
</LinearLayout>
核心代码:
private TextView mTvNumber;
private Edittext mEtComments;
@Override
protected void onCreate(){
super.onCreate();
initView();
initData();
}
private void initView(){
mTvNumber = findViewById(R.id.tv_number);
mEtComments = findViewById(R.id.et_comments);
}
private void initData(){
mEtComments.addTextChangeListener(new TextWatcher(){
//输入的文本
private CharSequence inputText;
//输入文本个数
private int inputTextNumber;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count){
inputText= s;
}
@Override
public void afterTextChanged(Editable s){
inputTextNumber= 500 - s.length();
mTvNumber.setText((500 - inputTextNumber) + "/500");
mTvNumber.setTextColor(Color.BLACK);
mEtComments.setTextColor(Color.BLACK);
if(inputText.length() > 500){
mTvNumber.setTextColor(Color.RED);
mEtComments.setTextColor(Color.RED);
//设置光标的位置
mEtComments.setSelection(mEtComments.getSelectionEnd());
}
}
});
}
如果有更好的意见,麻烦不吝赐教。