android 中如何限制 EditText 最大输入字符数(2)

方法四:

基本思路同方法三,监听 EditText 当中输入字符串的长度,如果超长,给出提示。

package cie.textEdit;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

public class TextEditActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		final EditText editText = (EditText)findViewById(R.id.entry);
		editText.addTextChangedListener(new TextWatcher(){
			private int selectionStart = 0;
			private int selectionEnd = 0;
			private CharSequence temp = null;
			
			public void afterTextChanged(Editable arg0) {
				// TODO Auto-generated method stub
				selectionStart = editText.getSelectionStart();
				selectionEnd = editText.getSelectionEnd();
				Log.i(myConstant.Tag,"selectionStart" + selectionStart);
				if(temp.length() > myConstant.TextMaxLen)
				{
					Toast.makeText(TextEditActivity.this, R.string.string_limit, Toast.LENGTH_SHORT).show();
					arg0.delete(selectionStart-1, selectionEnd);
					int tempSelection = selectionStart;
					editText.setText(arg0);
					editText.setSelection(tempSelection);
				}				
			}

			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				temp = arg0;
			}

			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}
			
		});
	}
}


当文本输入字符数10个,再输入字符时,就会出现





你可能感兴趣的:(Android,基础,android,class)