EditText (input box) detailed explanation


Introduction to this section:

In the previous section we learned about the first UI control TextView (text box). The article gives many possible encounters in actual development. Some of the needs The solution should bring convenience to your development. In this section, we will learn the second very commonly used control EditText (input box); Very similar to TextView, the biggest difference is: EditText can accept user input! As before, we will not talk about attributes one by one. We only talk about practical applications. If you want to deduct attributes, you can view the API documentation yourself: API Documentation; Then start this section!


1. Set the default prompt text

As shown below, I believe you are familiar with this user login interface, right? We use this interface many times

1.png

Compared with the other kind, how about the following one?

2.png

Not bad, right? Of course, I won’t post the layout here. Here we only introduce the two control attributes of the default prompt text:

Default prompt text The two attributes are as follows:

android:hint="Default prompt text"
android:textColorHint="#95A1AA"

The former sets the text content of the prompt , the latter sets the color of the prompt text!


2. After getting focus, select all text content in the component

When we click on our input box and get focus, we do not move the cursor to the beginning or end of the text. ; but Get all the text content in the input box! At this time we can use the selectAllOnFocus attribute

android:selectAllOnFocus="true"

For example, the following rendering: The first one has this attribute set, and the second one does not have this attribute set. After the EditText set to true gets focus All text is selected!

3.gif


3. Limit EditText input type

Sometimes we may need to limit the input data, such as when entering a phone number, you enter A string of letters, this Obviously it does not meet our expectations, and limiting the input type can be achieved through the inputType attribute!

For example, the limit can only be phone number, password (textPassword):

<EditText  
                                    android:layout_width="fill_parent"    
android:layout_height="wrap_content"
android:inputType="phone" />

可选参数如下:

文本类型,多为大写、小写和数字符号

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"

数值类型

android:inputType="number"  
android:inputType="numberSigned"  
android:inputType="numberDecimal"  
android:inputType="phone"//拨号键盘  
android:inputType="datetime"  
android:inputType="date"//日期键盘  
android:inputType="time"//时间键盘

4. Set the minimum line, maximum line, single line, multiple lines, and automatic line wrapping

EditText displays multiple lines by default and can automatically wrap. That is, when one line cannot be displayed completely, It will automatically switch to the second line

4.png

We can limit it, such as
Set the number of minimum lines: 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, many times we may have to restrict EditText to only allow single-line input and will not scroll, such as the login interface above. For example, we only need to set

android:singleLine="true"</p>
<p>
to achieve single-line input without line wrapping</p>

<hr />

<h2>5. Set the text spacing and set the capitalization type of English letters</h2>

<p>We can pass The following two attributes are used to set the spacing between words:
</p>
<pre>
android:textScaleX="1.5" //Set the horizontal spacing between words
android: textScaleY="1.5" //Set the vertical spacing between words

In addition, EditText also provides us with attributes for setting the capitalization type of English letters: android:capitalizeThe default is none, and three optional values ​​are provided:

  • sentences: Only the first letter is capitalized

  • words: The size of the first letter of each word, use spaces to distinguish words

  • #characters:Every English letter is capitalized


6. Control the spacing around EditText The distance between the internal text and the border

We use margin related attributes to increase the distance of the component relative to other controls, such as android:marginTop = "5dp" Use padding to increase the distance between the text in the component and the component border, such as android:paddingTop = "5dp"


##7. Set EditText to gain focus and pop up the small keyboard

Regarding this issue of EditText gaining focus and popping up the small keyboard, I struggled with it for a while in a recent project. The requirement is: after entering the Activity, let EditText gain focus and at the same time pop up a small keyboard for user input! I have tried many online methods but nothing works. I don’t know if it is because of the problem of the 5.1 system I am using! The following is a summary:

The first is to let EditText obtain focus and clear focus

edit.

requestFocus(); //Request to obtain focus edit.
clearFocus(); //Clear focus

After obtaining the focus, the small keyboard pops up. I spend most of my time on this:

  • In lower versions of the system, the small keyboard will automatically pop up by directly requestFocus

  • Slightly higher versions require us to manually play the keyboard: The first one:

##InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

Second type:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);
imm. hideSoftInputFromWindow(view.getWindowToken(), 0); //Force to hide the keyboard

I don’t know why, but the above two methods did not pop up the small keyboard. The author finally used: windowSoftInputMode attribute to solve the problem of popping up the small keyboard. Here I will share it with you:

android:windowSoftInputModeThe interaction mode between the Activity main window and the soft keyboard can be used to avoid the input method panel occlusion problem, a new feature after Android 1.5.
This attribute can affect two things:
[1] When focus is generated, whether the soft keyboard is hidden or displayed
[2] Whether to reduce the size of the active main window to make room for the soft keyboard

The simple point is the keyboard control when there is focus and whether to reduce the window size of Act to place the small keyboard
The following values ​​​​are available, and multiple values ​​​​can be set, separated by "|"
stateUnspecified: The state of the soft keyboard is not specified, the system will choose an appropriate state or depend on the theme settings
stateUnchanged: When this activity appears, the soft keyboard will Always maintain the state in the previous activity, whether hidden or displayed
stateHidden: When the user selects the activity, the soft keyboard is always hidden
stateAlwaysHidden: When the When the Activity main window gets focus, the soft keyboard is always hidden
stateVisible: The soft keyboard is usually visible
stateAlwaysVisible: When the user selects the activity, the soft keyboard Always displayed state
adjustUnspecified: Default setting, usually the system decides whether to hide or display
adjustResize: The Activity always adjusts the size of the screen to leave room for Soft keyboard space
adjustPan: The contents of the current window will be automatically moved so that the current focus is never covered by the keyboard and the user can always see part of the input content

We can set this property in AndroidManifest.xml for the Activity that needs to pop up the small keyboard, for example:

5.png

Then just requestFocus() on the EditText object~


8. Control of EditText cursor position

Sometimes we may need to control the cursor in EditText to move to a specified position or select some text!
EditText provides us with the setSelection() method. The method has two forms:

6.png
One parameter is to set the cursor position, and two parameters are is the enclosed part between setting the starting position and the ending position, that is, partially selected!
Of course we can also call setSelectAllOnFocus(true); to select all text when EditText gets focus!
In addition, we can also call setCursorVisible(false); to set the cursor not to be displayed.
We can also call getSelectionStart() and getSelectionEnd to obtain the current cursor. Front and rear position


9. Simple implementation of EditText with emoticons

I believe you are familiar with QQ or WeChat. When we send text, we can send it together with emoticons. There are two simple methods Implementation method:

1. Use SpannableString to implement
2. Use Html class to implement
Here the author uses the first one. Here only a simple effect is achieved. You can Extract the method and customize an EditText;
You can also write an input box yourself with multiple expression options similar to QQ!

Look at the renderings (click to add an expression to complete adding an expression):

7.png

The code is also very 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: By the way, don’t forget to put a picture~


10. EditText with delete button

We often see this on the input interface of the App:

8.png

#After we enter the content, such a small cross icon will appear on the right. After we click it, the content in the input box will be cleared!
It is actually very simple to implement:
Set addTextChangedListener for EditText, and then rewrite the abstract method in TextWatcher(), which is used to monitor changes in the input box; then setCompoundDrawablesWithIntrinsicBounds sets the picture of the small cross; finally, rewrite Write the onTouchEvent method. If the click area is the position of the small cross picture, clear the text!

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 EditTextWithDel(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(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                setDrawable();
            }
        });
        setDrawable();
    }

    // 设置删除图片
    private void setDrawable() {
        if (length() < 1)
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
        else
            setCompoundDrawablesWithIntrinsicBounds(null, null, imgInable, null);
    }

    // 处理删除事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (imgInable != 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 of this section:

This section introduces you to the EditText (input box) control in the Android UI control. There are many uses. Of course, the above situation will definitely not meet the actual needs. Actual development We may need to customize EditText according to our own needs! Of course, this involves the more advanced topic of custom controls. In the advanced part, we will explain the custom controls in Android in detail! Now you can use it~