Text Fields-文本框

Text Fields-文本框

主任务原文链接:http://docs.eoeandroid.com/guide/topics/ui/controls/text.html

目录

A text field allows the user to type text into your app. It can be either single line or multi-line. Touching a text field places the cursor and automatically displays the keyboard. In addition to typing, text fields allow for a variety of other activities, such as text selection (cut, copy, paste) and data look-up via auto-completion.
文本框允许用户在应用程序中输入文本。它们可以是单行的,也可以是多行的。点击文本框后显示光标,并自动显示键盘。除了输入,文本框还包含其它操作,比如文本选择(剪切,复制,粘贴)以及数据的自动查找功能。

You can add a text field to you layout with the EditText object. You should usually do so in your XML layout with a <EditText> element.
你可以使用EditText对象在布局中添加一个文本字段, android里的写法通常是在XML布局文件中添加<EditText>元素

edittext-noextract.png

Specifying the Keyboard Type-指定键盘类型

Text fields can have different input types, such as number, date, password, or email address. The type determines what kind of characters are allowed inside the field, and may prompt the virtual keyboard to optimize its layout for frequently used characters.
文本字段可以有不同的输入类型,如数字,日期,密码,或电子邮件地址。类型确定文本框内允许输入什么样的字符,可能会提示虚拟键盘调整其布局来显示最常用的字符。

You can specify the type of keyboard you want for your EditText object with the android:inputType attribute. For example, if you want the user to input an email address, you should use the textEmailAddress input type:

你可以在EditText对象使用Android:inputType属性指定输入类型的键盘,例如:你想输入一个电子邮件地址上的用户,inputType属性应为textEmailAddress:

edittext-text.png
图1:默认的文字输入类型。

 
<EditText
    android:id="@+id/email_address"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/email_hint"
    android:inputType="textEmailAddress" />

There are several different input types available for different situations. You can find them all listed with the documentation for android:inputType
针对不同的情况有几种不同的输入类型。你可以找到所有的文件中列出的android:inputType属性

edittext-email.png
图2:textEmailAddress输入类型。

Tip: To allow users to input long strings of text with line breaks, use the “textMultiLine” input type. By default, an EditText object is restricted to one line of text and scrolls horizontally when the text exceeds the available width.
提示:为了让用户输入长文本字符串时换行,使用的“textMultiLine”属性。默认情况下,一个编辑文本对象仅限于一行文本和水平滚动文本时超过可用宽度。

edittext-phone.png
图3:手机输入类型。

Controlling other behaviors-控制其他行为

The android:inputType also allows you to specify certain keyboard behaviors, such as whether to capitalize all new words or use features like auto-complete and spelling suggestions.
android:inputType还允许您指定操作行为,如在某此键盘上是否要利用所有新词,或使用自动完成和拼写建议功能。

The android:inputType attribute allows bitwise combinations so you can specify both a keyboard layout and one or more behaviors at once. For example, here’s how you can collect a postal address, capitalize each word, and disable text suggestions:
在android:inputType的属性允许按位组合,让您可以一次指定一个键盘布局和一个或多个操作行为。例如,你如何收集邮政地址,利用每一个字,并禁用文字的行为:

 
<EditText
    android:id="@+id/postal_address"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/postal_address_hint"
    android:inputType="textPostalAddress|
                       textCapWords|
                       textNoSuggestions" />

All behaviors are also listed with the android:inputType documentation.
还列出了所有的行为与Android的:inputType相关的文件。

Specifying Keyboard Actions-指定键盘操作

In addition to changing the keyboard’s input type, Android allows you to specify an action to be made when users have completed their input. The action specifies the button that appears in place of the carriage return key and the action to be made, such as “Search” or “Send.”
除了改变键盘的输入类型,当用户完成输入时,android允许你指定特殊的按钮进行相应的操作,如把回车键作为 “搜索”或 “发送”操作。

edittext-actionsend.png
图4:如果你声明的Android imeOptions =“actionSend” ,键盘包括发送的行动。

You can specify the action by setting the android:imeOptions attribute. For example, here’s how you can specify the Send action:
您可以通过android:imeOptions属性设置指定的动作。例如,这里你可以指定发送的行为:

 
<EditText
    android:id="@+id/search"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search_hint"
    android:inputType="text"
    android:imeOptions="actionSend" />

If you do not explicitly specify an input action then the system attempts to determine if there are any subsequent android:focusable fields. If any focusable fields are found following this one, the system applies the (@code actionNext} action to the current EditText so the user can select Next to move to the next field. If there’s no subsequent focusable field, the system applies the “actionDone” action. You can override this by setting the android:imeOptions attribute to any other value such as “actionSend” or “actionSearch” or suppress the default behavior by using the “actionNone” action.
如果你不明确指定一个输入动作,然后系统将尝试确定是否有任何后续的android:focusable属性动作。如果发现了有android:focusable属性动作,那么这个系统适用于在当前的EditText的(@code actionNext}行动,使用户可以选择“下一步”或移动到下一个字段。如果是没有后续的focusable属性,那该系统适用“actionDone “动作,你也可以通过设置Android:imeOptions属性使系统更改到其它值,如“actionSend”或“actionSearch”或禁止使用“actionNone”动作的默认行为。

Responding to action button events-响应按钮事件

If you have specified a keyboard action for the input method using android:imeOptions attribute (such as”actionSend”), you can listen for the specific action event using an TextView.OnEditorActionListener. The TextView.OnEditorActionListener interface provides a callback method called onEditorAction()that indicates the action type invoked with an action ID such as IME_ACTION_SEND or IME_ACTION_SEARCH.
如果您已指定键盘采用Android:imeOptions属性(“actionSend”等)的操作方法,你可以使用TextView.OnEditorActionListener监听事件行为。TextView.OnEditorActionListener接口提供了一个回调方法onEditorAction(),它通过输入的动作ID,如IME_ACTION_SEND或IME_ACTION_SEARCH行为调用相关的动作类型方法。

For example, here’s how you can listen for when the user clicks the Send button on the keyboard:
例如,你可以监听用户点击键盘上的发送按钮:

 
EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            // Send the user message
            handled = true;
        }
        return handled;
    }
});

Setting a custom action button label-设置文本框标签

If the keyboard is too large to reasonably share space with the underlying application (such as when a handset device is in landscape orientation) then fullscreen (“extract mode”) is triggered. In this mode, a labeled action button is displayed next to the input. You can customize the text of this button by setting the android:imeActionLabel attribute:
如果键盘太大,系统将会合理分担余下的应用程序(例如,当手机设备是横向的)空间,然后全屏(“提取模式”)被触发。在这种模式下,将在输入框旁边显示按钮,你可以通过设置imeActionLabel属性来定制按钮的文本。

 
<EditText
    android:id="@+id/launch_codes"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/enter_launch_codes"
    android:inputType="number"
    android:imeActionLabel="@string/launch" />

edittext-actionlabel.png
Figure 5. A custom action label with android:imeActionLabel
android:imeActionLabel属性案例

Adding Other Keyboard Flags-添加其他键盘标志

In addition to the actions you can specify with the android:imeOptions attribute, you can add additional flags to specify other keyboard behaviors. All available flags are listed along with the actions in the android:imeOptions documentation.
你可以指定Android:imeOptions属性添加另外的行为,你可以添加额外的标志,以指定其他键盘行为。在Android:imeOptions文件列出所有可用的标志。

For example, figure 5 shows how the system enables a fullscreen text field when a handset device is in landscape orientation (or the screen space is otherwise constrained for space). You can disable the fullscreen input mode with flagNoExtractUi in the android:imeOptions attribute, as shown in figure 6.
例如,图5显示的是当手机设备在横向屏幕上使用全屏文本字段时(或在屏幕上限制键盘空间)。您可以在Android:imeOptions属性设置flagNoExtractUi去禁用全屏输入模式,如图6所示。

edittext-noextract.png

Figure 6. The fullscreen text field (“extract mode”) is disabled with android:imeOptions=”flagNoExtractUi”.
android:imeOptions=”flagNoExtractUi”的提取模式

Providing Auto-complete Suggestions-提供自动完成建议

If you want to provide suggestions to users as they type, you can use a subclass of EditText called AutoCompleteTextView. To implement auto-complete, you must specify an (@link android.widget.Adapter) that provides the text suggestions. There are several kinds of adapters available, depending on where the data is coming from, such as from a database or an array.
如果你想向用户键入提供建议,您可以使用EditText的子类AutoCompleteTextView控件。为了实现自动完成,你必须指定一组(@link adndroid.widget.Adapter)文字提供建议。有几种可用的适配器,匹配数据项,如从数据库或一个数组获取所需要匹配值。

edittext-autocomplete.png
Figure 7. Example of AutoCompleteTextView with text suggestions
AutoCompleteTextView控件案例

The following procedure describes how to set up an AutoCompleteTextView that provides suggestions from an array, using ArrayAdapter:
下面的过程介绍了如何设置一个AutoCompleteTextView并使用ArrayAdapter适配器配置里面的所需的数组:

1.Add the AutoCompleteTextView to your layout. Here’s a layout with only the text field:
添加AutoCompleteTextView到您的布局。这里是只是一个文本字段的布局

 
<?xml version="1.0" encoding="utf-8"?>
<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/autocomplete_country"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

2.Define the array that contains all text suggestions. For example, here’s an array of country names that’s defined in an XML resource file (res/values/strings.xml):
定义一个数组,里面包含数组所需的子值。例如,这里是一个国家的名字,这是定义在一个XML资源文件(res/values/strings.xml)数组:

 
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="countries_array">
        <item>Afghanistan</item>
        <item>Albania</item>
        <item>Algeria</item>
        <item>American Samoa</item>
        <item>Andorra</item>
        <item>Angola</item>
        <item>Anguilla</item>
        <item>Antarctica</item>
        ...
    </string-array>
</resources>

3.In your Activity or Fragment, use the following code to specify the adapter that supplies the suggestions:
在Acitivity中或Fragment中,建议使用下面的代码操作适配器

 
// Get a reference to the AutoCompleteTextView in the layout
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
// Get the string array
String[] countries = getResources().getStringArray(R.array.countries_array);
// Create the adapter and set it to the AutoCompleteTextView 
ArrayAdapter<String> adapter = 
        new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);
textView.setAdapter(adapter);

Here, a new ArrayAdapter is initialized to bind each item in the COUNTRIES string array to a TextView that exists in the simple_list_item_1 layout (this is a layout provided by Android that provides a standard appearance for text in a list).
代码中,创建一个countries的数组,并将ArrayAdapter适配器初始化,且将其绑定到simple_list_item_1文件布局中(这是由Android提供一个文本框绑定数据的文本列表)。

Then assign the adapter to the AutoCompleteTextView by calling setAdapter().
然后AutoCompleteTextView属性调用setAdapter()方法,将适配器添加其中。

Leave a Comment