您的位置:首页 > 移动开发 > Android开发

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

2014-01-02 14:59 603 查看
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
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="@dimen/activity_vertical_margin" >

<EditText
android:id="@+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff" />

<TextView
android:layout_width="match_parent"
android:layout_height="1px"
android:layout_marginTop="8dp"
android:background="#000000"/>

</LinearLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: