Android basic tutorial -- 2.3.2 EditText (input box), androidedittext
Basic Android tutorial -- 2.3.2 EditText (input box)
Tags (separated by spaces): basic Android tutorial
This section introduces:
In the previous section, we learned the first UI control.TextView (text box)In this article, we provide some requirements that may be encountered in actual development.
The solution should be convenient for your development. In this section, we will learn the second commonly used control.EditText (input box);
Similar to TextView, the biggest difference is that EditText can be input by users! As before, we will not talk about attributes one by one,
Let's talk about the actual application only. If you want to deduct the attributes, you can view the API documentation: API documentation. Then start this section!
1. Set the default prompt text
For example, I believe you are no stranger to such user logon interfaces.
What about the following?
The layout will not be pasted here. Here we will only introduce the two control attributes of the default prompt text:
The two attributes of the prompt text are as follows by default:
Android: hint = "default prompt text" android: textColorHint = "# 95A1AA"
The former sets the text content of the prompt, and the latter sets the color of the prompt text!
2. Select all text content in the component after obtaining the focus
When we click to get the focus in our input box, we do not move the cursor to the beginning or end of the text; instead
Obtain all text in the input box! In this case, we can useSelectAllOnFocusAttribute
android:selectAllOnFocus="true"
For example:
The first is set for this attribute, and the second is not set for this attribute. After EditText set to true gets the focus
All texts are selected!
3. Restrict the EditText input type
Sometimes we may need to restrict the input data. For example, when you enter a phone number, you enter a letter.
Obviously, this is not what we expected, and the inputType attribute can be used to limit the input type!
For example, only the phone number and password (TextPassword):
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="phone" />
The optional parameters are as follows:
Text Type, mostly uppercase, lowercase, and numeric characters
android:inputType="none" android:inputType="text" android:inputType="textCapCharacters" android:inputType="textCapWords" android:inputType="textCapSentences" android:inputType="textAutoCorrect" android:inputType="textAutoComplete" android:inputType="textMultiLine" android:inputType="textImeMultiLine" android:inputType="textNoSuggestions" android:inputType="textUri" android:inputType="textEmailAddress" android:inputType="textEmailSubject" android:inputType="textShortMessage" android:inputType="textLongMessage" android:inputType="textPersonName" android:inputType="textPostalAddress" android:inputType="textPassword" android:inputType="textVisiblePassword" android:inputType="textWebEditText" android:inputType="textFilter" android:inputType="textPhonetic"
Value Type
Android: inputType = "number" android: inputType = "numberSigned" android: inputType = "numberDecimal" android: inputType = "phone" // dial-up keyboard android: inputType = "datetime" android: inputType = "date" // date keyboard android: inputType = "time" // time keyboard
4. Set the minimum line, maximum line, single line, multiple lines, and automatic line feed.
EditText is displayed in multiple rows by default and can be automatically wrapped. That is, when one row cannot be displayed, it is automatically switched to the second line.
We can restrict it, for example
Set the minimum number of rows:Android: minLines = "3"
Or set the maximum number of lines in EditText:Android: maxLines = "3"
PS: when the input content exceeds maxline, the text will automatically scroll up !!
In addition, in many cases, we may want to restrict EditText to only allow single-line input without scrolling. For example
For example, we only need to set
android:singleLine="true"
You can achieve single-line input without line breaks
5. Set the text interval and uppercase letters
We can use the following two attributes to set the word Spacing:
Android: textScaleX = "1.5" // sets the horizontal interval between words. android: textScaleY = "1.5" // sets the vertical interval between words and words.
In addition, EditText also provides the attributes for setting uppercase letters:Android: capitalize
The default value is none. Three Optional values are provided:
- Sentences:Only the first letter is capitalized.
- Words:The size of the first letter of each word. Separate words with spaces.
- Characters:Each letter is capitalized.
6. Control the distance between the four sides of EditText and the distance between the internal text and the border
We useMarginRelated Properties increase the distance between components and other controls, such as android: marginTop = "5dp"
UsePaddingIncrease the distance between the text in the component and the widget border, for example, android: paddingTop = "5dp"
7. Set EditText to get the focus, and a keyboard pops up.
Concerning the problem of getting the focus of this EditText and the pop-up of the keypad, the previous project had struggled with the author for a while.
Requirement: after entering the Activity, let EditText get the focus, and a keyboard is displayed for users to enter!
I tried a lot of methods on the Internet, but I don't know if it's because of my 5.1 system problems!
Below is a summary:
First, let EditText get focus and clear focus
Edit.RequestFocus(); // Request to get the focus
Edit.ClearFocus(); // Clear focus
After getting the focus, the keyboard pops up and I spend most of my time on it:
- In earlier versions, the system directly uses requestFocus to automatically pop up the keypad.
- For a slightly higher version, we need to manually play the keyboard:
First:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
Second:
InputMethodManager imm = (InputMethodManager) getSystemService (Context. INPUT_METHOD_SERVICE); imm. showSoftInput (view, InputMethodManager. SHOW_FORCED); imm. hideSoftInputFromWindow (view. getWindowToken (), 0); // force hide the keyboard
I don't know why. The above two methods didn't bring up the keypad. I finally used it:WindowSoftInputModeAttribute solves the problem of pop-up keypad. Here we will share with you:
Android: windowSoftInputMode
The interaction mode between the Activity main window and the soft keyboard can be used to avoid the problem of blocking the input method panel. This is a new feature after Android1.5.
This attribute can affect two things:
[1] whether the keyboard is hidden or displayed when a focus is generated
[2] whether to reduce the size of the main activity window to free up space and put it on the keyboard
The simple point is the keyboard control with focus and whether to reduce the size of the Act window.
The following values are available. You can set multiple values separated by "| ".
StateUnspecified: The keyboard status is not specified. The system selects an appropriate status or a topic-dependent setting.
StateUnchanged: When this activity appears, the soft keyboard will remain in the status of the previous activity, whether hidden or displayed
StateHidden: When you select activity, the keyboard is always hidden.
StateAlwaysHidden: When the main Activity window gets the focus, the keyboard is always hidden.
StateVisible: The keyboard is usually visible.
StateAlwaysVisible: When you select activity, the soft keyboard always displays the status
AdjustUnspecified: Default settings. The system determines whether to hide or display the settings.
AdjustResize: This Activity always adjusts the screen size to reserve space for the soft keyboard.
AdjustPan: The content of the current window is automatically moved so that the current focus is not overwritten by the keyboard and the user can always see the part of the input content.
In AndroidManifest. xml, we can set this attribute for the Activity that requires a keyboard to pop up, for example:
Then the EditText object requestFocus () will be ready ~
8. EditText Cursor Position Control
Sometimes we may need to control the cursor in EditText to move to the specified position or select some text!
EditText provides usSetSelection() Method, the method has two forms:
One parameter is used to set the cursor position. The two parameters are used to set the center of the start and end positions, that is, partially selected!
Of course, we can also callSetSelectAllOnFocus (true); Select all text when EditText gets focus!
You can also callSetCursorVisible (false); Set the cursor not to display
You can also call g ** etSelectionStart ()And ** getSelectionEndObtains the front and back positions of the current cursor.
9. Simple implementation of EditText with emoticon
I believe you are familiar with QQ or QQ. When sending text, you can send it together with your facial expression. There are two simple implementation methods:
1. Use SpannableString to implement
2. Use Html classes to implement
Here I use the first method. Here we only implement a simple effect. You can extract the method and customize an EditText;
You can also write an input box that has multiple emoticons similar to QQ!
Click "add emoticon" to add the emoticon ):
The Code is also simple:
public class MainActivity extends Activity { private Button btn_add; private EditText edit_one; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_add = (Button) findViewById(R.id.btn_add); edit_one = (EditText) findViewById(R.id.edit_one); btn_add.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SpannableString spanStr = new SpannableString("imge"); Drawable drawable = MainActivity.this.getResources().getDrawable(R.drawable.f045); drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight()); ImageSpan span = new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE); spanStr.setSpan(span,0,4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); int cursor = edit_one.getSelectionStart(); edit_one.getText().insert(cursor, spanStr); } }); }}
PS: Right. Don't forget to put an image ~
10. EditText with the delete button
We often see the following on the App input interface:
When we enter the content, the right side of the interface will display such a little cross icon, we click it to clear the content in the input box!
The implementation is actually very simple:
Set addTextChangedListener for EditText, and then rewrite the abstract method in TextWatcher (). This method is used to listen to changes in the input box. Then setCompoundDrawablesWithIntrinsicBounds sets the image of the Cross. Finally, rewrite the onTouchEvent, clear the text if you click the image in the image area!
The implementation code is as follows:
Public class EditTextWithDel extends EditText {private final static String TAG = "EditTextWithDel"; private Drawable imgInable; private Drawable imgAble; private Context mContext; public EditTextWithDel (Context context) {super (context ); mContext = context; init ();} public EditTextWithDel (Context context, AttributeSet attrs) {super (context, attrs); mContext = context; init ();} public EditTextWi ThDel (Context context, AttributeSet attrs, int defStyleAttr) {super (context, attrs, defStyleAttr); mContext = context; init ();} private void init () {imgInable = mContext. getResources (). getDrawable (R. drawable. delete_gray); addTextChangedListener (new TextWatcher () {@ Override public void onTextChanged (CharSequence s, int start, int before, int count) {}@ Override public void beforeTextChanged (Ch ArSequence s, int start, int count, int after) {}@ Override public void afterTextChanged (Editable s) {setDrawable () ;}}); setDrawable ();} // set the private void setDrawable () {if (length () <1) values (null, null); else setCompoundDrawablesWithIntrinsicBounds (null, null, imgInable, null);} // process the deletion event @ Override public boolean onTouchEvent (MotionEvent Event) {if (imgAble! = Null & event. getAction () = MotionEvent. ACTION_UP) {int eventX = (int) event. getRawX (); int eventY = (int) event. getRawY (); Log. e (TAG, "eventX =" + eventX + "; eventY =" + eventY); Rect rect = new Rect (); getGlobalVisibleRect (rect); rect. left = rect. right-100; if (rect. contains (eventX, eventY) setText ("");} return super. onTouchEvent (event) ;}@ Override protected void finalize () throws Throwable {super. finalize ();}}
Summary:
This section introduces the EditText (input box) control in the Android UI control. There are many usage options. Of course, the above situations certainly cannot meet the actual needs, in actual development, we may need to customize EditText as needed! Of course, this involves the advanced topic of the custom control. In the advanced section, we will explain in detail the custom control in Android! You can use it now ~
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.