Android EditText 只能输入三行文本的实现方法


MainActivity.java
package com.example.edittext;

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

public class MainActivity extends Activity {

	private EditText et;
	protected boolean editable = true;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
		setContentView(R.layout.activity_main);
		
		et = (EditText)findViewById(R.id.et);
		
		et.addTextChangedListener(new TextWatcher() {
			
			CharSequence beforeText = null;
			private int line;
			
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {} 
			public void afterTextChanged(Editable s) {}
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// 判断是增加还是删除  
				
				StringBuilder sb = new StringBuilder(s);
				beforeText = sb.delete(start, start+count).toString();

				line = et.getLineCount();
				if (line >= 4) { 
					
					Toast.makeText(MainActivity.this, 
							"最多只能输入三行", Toast.LENGTH_SHORT).show();
	
					int length = beforeText.length();
					et.setText(beforeText.toString());
					et.setSelection(length);
				} 
			}
		});
	}
}

activity_main.xml


    

    
    



你可能感兴趣的:(android)