Search code examples
androidandroid-layoutmaterial-designandroid-support-libraryandroiddesignsupport

How to reset floating label text to its' original position when clicked outside of Text Input Layout android


Hi I'm using floating text views for my layout. When I click on the edit text and input nothing or delete every thing inside the edit text and then click outside of that view my floating label still remains at the elevated position. I want to reset its position as it was before where there is hint displaying and no text inserted. So how to achieve this ? Thanks in advance.

And I'm using support design library for displaying floating labels.

I'm following this tutorial for the floating labels.

enter image description here


Solution

  • You can add some code to your activity to make edittexts lose focus after any click outside them. Here is an example:

    public static void setupForKeyboardDismiss(View view, final Activity activity) {
    
            //Set up touch listener for non-text box views to hide keyboard.
            if(!(view instanceof EditText)) {
    
                view.setOnTouchListener(new View.OnTouchListener() {
    
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(activity);
                        return false;
                    }
    
                });
            }
    
            //If a layout container, iterate over children and seed recursion.
            if (view instanceof ViewGroup) {
    
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
    
                    View innerView = ((ViewGroup) view).getChildAt(i);
    
                    setupForKeyboardDismiss(innerView, activity);
                }
            }
        }
        public static void hideSoftKeyboard(Activity activity) {
            try {
                InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    

    Then you can call setupForKeyboardDismiss method passing any view that contains those edittexts, actually you can apply it on all the activity by calling this (after the setContentView of your activity):

    setupForKeyboardDismiss((ViewGroup) activity.findViewById(android.R.id.content), activity);