Android EditText使用详解

新建HelloEditText工程

转载自:Android EditText使用详解

新建一个Hello world详细步骤可以参见
Android教程之三:第一个Android应用,HelloWorld
创建设置如下:

  • Project name: HelloEditText
  • Build Target :android 2.2
  • Application name:HelloEditText
  • Package name:com.flysnow
  • create Activity: HelloEditText
  • min SDK 8

这时候运行还看不到EditText,因为我们还没有加上,修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="这是一个EditText"/>  
</LinearLayout>

这里添加了一个id为”edit_text”的EditText,设置默认显示为本为“这是一个EditText”。。运行效果如下:
这里写图片描述

EditText简介

EditText是一个非常重要的组件,可以说它是用户和Android应用进行数据传输窗户,有了它就等于有了一扇和Android应用传输的门,通过它用户可以把数据传给Android应用,然后得到我们想要的数据。
EditText是TextView的子类,所以TextView的方法和特性同样存在于EditText中,具体的TextView的介绍可以参考上一节Android系列教程之六:TextView小组件的使用–附带超链接和跑马灯效果

长度和空白提示文字,提示文字颜色,是否可编辑等

1.EditText有一些属性可以设置EditText的特性,比如最大长度,空白提示文字等。
有时候我们有一些特属的需要,要求只能在EditText中输入特定个数的字符,比如身份证号、手机号吗等。这时候就可以通过android:maxLength属性来设置最大输入字符个数,比如android:maxLength=“4”就表示最多能输入4个字符,再多了就输入不进去了。
2.空白提示文字。有时候我们需要说明你定义的这个EditText是做什么用的,比如让输入“用户名”,或者输入“电话号码”等,但是你又不想在EditText前面加一个TextView来说明这是输入“用户名”的,因为这会使用一个TextView,那么怎么办呢?EditText为我们提供了android:hint来设置当EditText内容为空时显示的文本,这个文本只在EditText为空时显示,你输入字符的时候就消失了,不影响你的EditText的文本。。修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:maxLength="40"  
    android:hint="请输入用户名..."/>  
</LinearLayout> 

运行应用就会看到如下的效果:
这里写图片描述

看看吧,简洁明了还不用新增一个TextView说明,也不影响用户操作。

3.上面列出了空白时的提示文字,有的人说了,我不想要这个灰色的提示文字,和我的应用整体风格不协调,那也行啊,我们可以换颜色,怎么换呢,就是通过android:textColorHint属性设置你想要的颜色。修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:maxLength="40"  
    android:hint="请输入用户名..."  
    android:textColorHint="#238745"/>  
</LinearLayout> 

运行程序效果如下:
这里写图片描述

4.还有一个比较实用的功能,就是设置EditText的不可编辑。设置android:enabled=”false”可以实现不可编辑,可以获得焦点。这时候我们看到EditText和一个TextView差不多:
这里写图片描述

5.实现类似html中Textarea的文本域。在Android中没有专门的文本域组件,但是可以通过设置EditText的高来实现同样的文本域功能。修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="200dip"/>  
</LinearLayout>  

运行程序效果如下:
这里写图片描述

输入特殊格式的字符

在我们开发程序的时候不免会输入一些特属个数的字符,比如密码(输入框的字符要加密显示),电话号码(比如数字和-),数字等,这些都算是一些特属格式的字符,强大的EditText同样为我们提供了输入这些特属格式字符的设置。
1.密码文本框。密码输入也是Android应用常用的功能,通过配置EditText的android:password=”true”就可以实现这一密码输入功能,修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:password="true"/>  
</LinearLayout> 

运行效果如下:
这里写图片描述

可以看到我们输入的字符已经被“.”这样的掩码所代替。
2.手机中发短信打电话是必不可少的,所以用于专门输入电话号码的文本框也是大有用途,有了他我们对是否是电话号码的校验就容易的多了(因为字符是正确的,只要校验格式 ).通过设置android:phoneNumber=”true”就可以把EditText变成只接受电话号码输入的文本框,连软键盘都已经变成拨号专用软键盘了,所以不用再担心输入其他字符了。修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:phoneNumber="true"/>  
</LinearLayout>

运行程序效果如下:
这里写图片描述

注意看软键盘,已经变成拨号专用的啦.

3.有时候我们只想输入数字,不想输入字母,EditText为我们提供了android:numeric来控制输入的数字类型,一共有三种分别为integer(正整数)、signed(带符号整数)和decimal(浮点数)。这里以signed类型的为例,修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:numeric="signed"/>  
</LinearLayout> 

运行效果如下:
这里写图片描述
注意这里的软键盘变成“数字键盘”的变化.

为文本指定特定的软键盘类型

前面我们通过指定为电话号码特定格式,然后键盘类型变成了拨号专用的键盘,这个是自动变的,其实我们也可以通过android:inputType来设置文本的类型,让输入法选择合适的软键盘的。。android:inputType有很多类型,这里使用date类型来演示,修改main.xml如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:inputType="date"/>  
</LinearLayout> 

运行效果如下:
这里写图片描述

Enter键图标的设置

软键盘的Enter键默认显示的是“完成”文本,我们知道按Enter建表示前置工作已经准备完毕了,要去什么什么啦。比如,在一个搜索中,我们输入要搜索的文本,然后按Enter表示要去搜索了,但是默认的Enter键显示的是“完成”文本,看着不太合适,不符合搜索的语义,如果能显示“搜索”两个字或者显示一个表示搜索的图标多好。事实证明我们的想法是合理的,Android也为我们提供的这样的功能。通过设置android:imeOptions来改变默认的“完成”文本。这里举几个常用的常量值:

  • actionUnspecified 未指定,对应常量EditorInfo.IME_ACTION_UNSPECIFIED.效果:这里写图片描述
  • actionNone 没有动作,对应常量EditorInfo.IME_ACTION_NONE 效果:这里写图片描述
  • actionGo 去往,对应常量EditorInfo.IME_ACTION_GO 效果:这里写图片描述
  • actionSearch 搜索,对应常量EditorInfo.IME_ACTION_SEARCH 效果:这里写图片描述
  • actionSend 发送,对应常量EditorInfo.IME_ACTION_SEND 效果:这里写图片描述
  • actionNext 下一个,对应常量EditorInfo.IME_ACTION_NEXT 效果:这里写图片描述
  • actionDone 完成,对应常量EditorInfo.IME_ACTION_DONE 效果:这里写图片描述

    <?xml version="1.0" encoding="utf-8"?>  
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        android:orientation="vertical"  
        android:layout_width="fill_parent"  
        android:layout_height="fill_parent"  
        >  
    <EditText  
        android:id="@+id/edit_text"    
        android:layout_width="fill_parent"   
        android:layout_height="wrap_content"  
        android:imeOptions="actionSearch"/>  
    </LinearLayout> 
    

修改HelloEditText如下:

package com.flysnow;  

import android.app.Activity;  
import android.os.Bundle;  
import android.view.KeyEvent;  
import android.widget.EditText;  
import android.widget.TextView;  
import android.widget.Toast;  
import android.widget.TextView.OnEditorActionListener;  

public class HelloEditText extends Activity {  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        EditText editText=(EditText)findViewById(R.id.edit_text);  
        editText.setOnEditorActionListener(new OnEditorActionListener() {  
            @Override  
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
                Toast.makeText(HelloEditText.this, String.valueOf(actionId), Toast.LENGTH_SHORT).show();  
                return false;  
            }  
        });  
    }  
}  

运行程序,点击回车(也就是搜索图标软键盘按钮)会显示该actionId.我们上面的每一个设置都会对应一个常量,这里的actionId就是那个常量值。
这里写图片描述

EditText的取值、全选、部分选择、获取选中文本

下面通过一个例子来演示EditText的取值、全选、部分选择和获取选中文本.main.xml修改如下:

<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical"  
    android:layout_width="fill_parent"  
    android:layout_height="fill_parent"  
    >  
<EditText  
    android:id="@+id/edit_text"    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"  
    android:imeOptions="actionSearch"/>  
<Button   
    android:id="@+id/btn_get_value"  
    android:text="取值"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"/>  
<Button   
    android:id="@+id/btn_all"  
    android:text="全选"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"/>  
<Button   
    android:id="@+id/btn_select"  
    android:text="从第2个字符开始选择"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"/>  
<Button   
    android:id="@+id/btn_get_select"  
    android:text="获取选中文本"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"/>  
</LinearLayout> 

HelloEditText修改如下:

package com.flysnow;  

import android.app.Activity;  
import android.os.Bundle;  
import android.text.Editable;  
import android.text.Selection;  
import android.view.KeyEvent;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.EditText;  
import android.widget.TextView;  
import android.widget.Toast;  
import android.widget.TextView.OnEditorActionListener;  

public class HelloEditText extends Activity {  

    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        final EditText editText=(EditText)findViewById(R.id.edit_text);  
        //监听回车键  
        editText.setOnEditorActionListener(new OnEditorActionListener() {  
            @Override  
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {  
                Toast.makeText(HelloEditText.this, String.valueOf(actionId), Toast.LENGTH_SHORT).show();  
                return false;  
            }  
        });  
        //获取EditText文本  
        Button getValue=(Button)findViewById(R.id.btn_get_value);  
        getValue.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                Toast.makeText(HelloEditText.this, editText.getText().toString(), Toast.LENGTH_SHORT).show();  
            }  
        });  
        //让EditText全选  
        Button all=(Button)findViewById(R.id.btn_all);  
        all.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                editText.selectAll();  
            }  
        });  
        //从第2个字符开始选择EditText文本  
        Button select=(Button)findViewById(R.id.btn_select);  
        select.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                Editable editable=editText.getText();  
                Selection.setSelection(editable, 1,editable.length());  
            }  
        });  
      //获取选中的文本  
        Button getSelect=(Button)findViewById(R.id.btn_get_select);  
        getSelect.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
                int start=editText.getSelectionStart();  
                int end=editText.getSelectionEnd();  
                CharSequence selectText=editText.getText().subSequence(start, end);  
                Toast.makeText(HelloEditText.this, selectText, Toast.LENGTH_SHORT).show();  
            }  
        });  
    }  

    protected void switchIndex(int start, int end) {  
        int temp=start;  
        start=end;  
        end=temp;  
    }  
}

运行效果如下:
这里写图片描述

可以通过输入文字和点击下面的按钮测试。

转载自:Android:EditText

Android的编辑框控件EditText在平常编程时会经常用到,有时候会对编辑框增加某些限制,如限制只能输入数字,最大输入的文字个数,不能输入一些非法字符等,这些需求有些可以使用android控件属性直接写在布局xml文件里,比如android:numeric=”integer”(只允许输入数字);

对于一些需求,如非法字符限制(例如不允许输入#号,如果输入了#给出错误提示),做成动态判断更方便一些,而且容易扩展;

在Android里使用TextWatcher接口可以很方便的对EditText进行监听;TextWatcher中有3个函数需要重载:

 public void beforeTextChanged(CharSequence s, int start,
                                  int count, int after);
 public void onTextChanged(CharSequence s, int start, int before, int count);
 public void afterTextChanged(Editable s);

从函数名就可以知道其意思,每当敲击键盘编辑框的文字改变时,上面的三个函数都会执行,beforeTextChanged可以给出变化之前的内容,onTextChanged和afterTextChanged给出追加上新的字符之后的文本;

所以对字符的限制判断可以在afterTextChanged函数中进行,如果检查到新追加的字符为认定的非法字符,则在这里将其delete掉,那么他就不会显示在编辑框里了:

private final TextWatcher mTextWatcher = new TextWatcher() {
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    } 

    public void onTextChanged(CharSequence s, int start, int before, int count) {
    } 

    public void afterTextChanged(Editable s) {
        if (s.length() > 0) {
            int pos = s.length() - 1;
            char c = s.charAt(pos);
            if (c == '#') {
//这里限制在字串最后追加#
                s.delete(pos,pos+1);
                Toast.makeText(MyActivity.this, "Error letter.",Toast.LENGTH_SHORT).show();
            }
        }
    }
};

注册监听:

EditText mEditor = (EditText)findViewById(R.id.editor_input);
mEditor.addTextChangedListener(mTextWatcher);

android 中如何限制 EditText 最大输入字符数:

方法一:

在 xml 文件中设置文本编辑框属性作字符数限制

如:android:maxLength=”10” 即限制最大输入字符个数为10

方法二:

在代码中使用InputFilter 进行过滤

//editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)}); 即限定最大输入字符数为20

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); 

        EditText editText = (EditText)findViewById(R.id.entry); 
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)}); 
    } 
} 

方法三:

利用 TextWatcher 进行监听

package cie.textEdit; 

import android.text.Editable; 
import android.text.Selection; 
import android.text.TextWatcher; 
import android.widget.EditText; 

/*
* 监听输入内容是否超出最大长度,并设置光标位置
* */ 
public class MaxLengthWatcher implements TextWatcher { 

    private int maxLen = 0; 
    private EditText editText = null; 


    public MaxLengthWatcher(int maxLen, EditText editText) { 
        this.maxLen = maxLen; 
        this.editText = editText; 
    } 

    public void afterTextChanged(Editable arg0) { 
        // TODO Auto-generated method stub 

    } 

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

    } 

    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { 
        // TODO Auto-generated method stub 
        Editable editable = editText.getText(); 
        int len = editable.length(); 

        if(len > maxLen) 
        { 
            int selEndIndex = Selection.getSelectionEnd(editable); 
            String str = editable.toString(); 
            //截取新字符串 
            String newStr = str.substring(0,maxLen); 
            editText.setText(newStr); 
            editable = editText.getText(); 

            //新字符串的长度 
            int newLen = editable.length(); 
            //旧光标位置超过字符串长度 
            if(selEndIndex > newLen) 
            { 
                selEndIndex = editable.length(); 
            } 
            //设置新光标所在的位置 
            Selection.setSelection(editable, selEndIndex); 

        } 
    } 

} 

对应的 activity 部分的调用为:

package cie.textEdit; 

import android.app.Activity; 
import android.os.Bundle; 
import android.text.InputFilter; 
import android.widget.EditText; 

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); 

        EditText editText = (EditText) findViewById(R.id.entry); 
        editText.addTextChangedListener(new MaxLengthWatcher(10, editText)); 

    } 
} 

限制输入字符数为10个

main.xml 文件

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <TextView 
        android:id="@+id/label" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Type here:"/> 
    <EditText 
        android:id="@+id/entry" 
        android:singleLine="true" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:background="@android:drawable/editbox_background" 
        android:layout_below="@id/label"/> 
    <Button 
        android:id="@+id/ok" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_below="@id/entry" 
        android:layout_alignParentRight="true" 
        android:layout_marginLeft="10dip" 
        android:text="OK" /> 
    <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_toLeftOf="@id/ok" 
        android:layout_alignTop="@id/ok" 
        android:text="Cancel" /> 
</RelativeLayout> 

效果为输入了10个字符后,光标停在末尾
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值