1、main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<EditText
android:gravity="top"
android:id="@+id/et"
android:layout_width="fill_parent"
android:layout_height="200dp" />
<TextView
android:layout_below="@id/et"
android:layout_alignParentRight="true"
android:id="@+id/tv"
android:layout_marginRight="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="还可输入10字" />
</RelativeLayout>
2、MainActivity
package forrest.foreditlimit;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText et;
private TextView tv;
private int limitNum = 10;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
setListener();
}
private void setListener() {
et.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void afterTextChanged(Editable s) {
if (s.length() > limitNum) {
// 不能输入
s.delete(limitNum, limitNum+1);
et.setText(s);
et.setSelection(limitNum);
} else {
tv.setText("还可输入" + (limitNum - s.length()) + "字");
}
}
});
}
private void init() {
et = (EditText) findViewById(R.id.et);
tv = (TextView) findViewById(R.id.tv);
}
}
完整代码: http://download.csdn.net/detail/wo334499/5025510