1.通过添加<EditText>
来添加一个可编辑的文本框。
2.通过更改android:inputType
属性来更改EditText的输入类型和输入时键盘的布局,如:
<EditText android:id="@+id/email_address" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="@string/email_hint" android:inputType="textEmailAddress" />
所有的输入类型都在android:inputType 下,如textUri,textEmailAddress等等。并且可以使用"|"来同时使用多种,如:
<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" />
当输入较长的字符串时,使用textMultiLine比较好。
3.定制键盘的Actions,使用android:imeOptions="actionSend"
,如:
<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" />
效果如图:![]()
当随后的文本是
android:focusable
时,系统默认动作为actionNext;如果不是,则默认actionDone
动作。也可以使用
actionNone
来阻止使用Action。
4.响应动作按钮事件:
为EditText添加一个
OnEditorActionListener
监听器,并重写onEditorAction方法,如: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; } });
5.定制按钮的label:
使用
android: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" />
效果如图:
6.使用自动完成的文本框(AutoCompleteTextView
):
效果如图:
使用方法:
①添加
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" />
②定义包含文字提示的数组,并保存到
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>
③在Activity中指定适配器:
// 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);