Clear edittext focus and hide keyboard when button is pressed

前端 未结 4 2132
伪装坚强ぢ
伪装坚强ぢ 2021-02-10 06:04

I\'m making an app with edittext and a button. When I enter something into edittext and then click a button, I want the keyboard and focus on edittext to disappear but I can\'t

相关标签:
4条回答
  • 2021-02-10 06:27

    First you must disable the keyboard:

    void hideKeyboard(Activity activity) { View view = activity.getCurrentFocus(); InputMethodManager manager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); assert manager != null && view != null; manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); }

    Second clear view (Layout, EditText...)focus:

    view.clearFocus

    0 讨论(0)
  • 2021-02-10 06:31

    another solution is, create a dummy layout

    <!-- Dummy item for focus at startup -->
    <LinearLayout
        android:id="@+id/dummy_id"
        android:orientation="vertical"
        android:layout_width="0px"
        android:layout_height="0px"
        android:focusable="true"
        android:focusableInTouchMode="true" />
    

    and set the focus in your onButtonClickFunction

    ((LinearLayout) findViewById(R.id.dummy_id)).requestFocus();
    
    0 讨论(0)
  • 2021-02-10 06:34

    To hide the keyboard call this:

    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(edittext.getWindowToken(), 0);
    

    You can also check this solution: https://stackoverflow.com/a/15587937/786337

    0 讨论(0)
  • 2021-02-10 06:38
    InputMethodManager inputManager = (InputMethodManager)
                                      getSystemService(Context.INPUT_METHOD_SERVICE); 
    
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                                         InputMethodManager.HIDE_NOT_ALWAYS);
    editText.setText("");
    

    Add the following on your button onclick event

    You need to import android.view.inputmethod.InputMethodManager;

    The keyboard hides and clears the text when you click the button.

    0 讨论(0)
提交回复
热议问题