How can I set the focus (and display the keyboard) on my EditText programmatically

后端 未结 13 811
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 02:22

I have a layout which contains some views like this:






&         


        
13条回答
  •  执念已碎
    2020-11-28 02:35

    Here is KeyboardHelper Class for hiding and showing keyboard

    import android.content.Context;
    import android.view.View;
    import android.view.inputmethod.InputMethodManager;
    import android.widget.EditText;
    
    /**
     * Created by khanhamza on 06-Mar-17.
     */
    
    public class KeyboardHelper {
    public static void hideSoftKeyboard(final Context context, final View view) {
        if (context == null) {
            return;
        }
        view.requestFocus();
        view.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null;
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    }, 1000);
    }
    
    public static void hideSoftKeyboard(final Context context, final EditText editText) {
        editText.requestFocus();
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null;
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
    }, 1000);
    }
    
    
    public static void openSoftKeyboard(final Context context, final EditText editText) {
        editText.requestFocus();
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null;
    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
    }
    }, 1000);
    }
    }
    

提交回复
热议问题