Android learning notes-EditText (input box) (2), android-edittext

Source: Internet
Author: User

Android learning notes-EditText (input box) (2), android-edittext

Reference: http://www.runoob.com/w3cnote/android-tutorial-edittext.html

 

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"PaddingIncrease the distance between the text 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, the pop-up keypad is not long ago, the project has struggled with the author's demand for a period of time: after entering the Activity, let the EditText get the focus, and the pop-up keypad 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, you 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

Android: windowSoftInputModeThe 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 gEtSelectionStart ()AndGetSelectionEndObtains 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 (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 ();}}

 

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"PaddingIncrease the distance between the text 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, the pop-up keypad is not long ago, the project has struggled with the author's demand for a period of time: after entering the Activity, let the EditText get the focus, and the pop-up keypad 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, you need to manually play the keyboard: first:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.