EditText字数限制及状态判断
开发工具:Eclipse
AVM:夜神模拟器
效果图:
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.wentong.administrator.zt.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp"
android:gravity="center">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/act_main_et"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="@color/colorAccent" - 背景色
android:hint="请输入"
android:gravity="top|left" - 输入框内字体位置
android:textSize="12sp" - 输入框内字体大小
android:textColor="@color/colorPrimary" - 输入框内字体颜色
android:maxLength="100"/> - 输入框内字数限制
<TextView
android:id="@+id/act_main_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="字数:100"
android:layout_gravity="bottom|right"/>
</FrameLayout>
</LinearLayout>
</RelativeLayout>
Activity:
package com.wentong.administrator.zt;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
private EditText et ;
private TextView tv ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//静态加载布局
setContentView(R.layout.activity_main);
//初始化控件
initView() ;
}
private void initView() {
//绑定控件
et = (EditText) findViewById(R.id.act_main_et) ;
tv = (TextView) findViewById(R.id.act_main_tv) ;
//为EditText添加监听
et.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) {
int num = 100 - s.length() ;
tv.setText("字数:" + num);
}
});
}
}
总结:
如果我们只是想要字数限制:android:maxLength="最大字数"
如果我们需要对EditText里面的字数进行监听:
EditText.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) {
//s.length()输入框内的字数
int num = 100 - s.length() ;
tv.setText("字数:" + num);
}
});
EditText状态判断:
今天在开发中遇到需要判断EditText是显示的状态还是隐藏的状态
EditText.getVisibility() == 0 ;//VISIBLE
EditText.getVisibility() == 4 ;//INVISIBLE
EditText.getVisibility() == 8 ;//GONE