Подтвердить что ты не робот

Как показать/скрыть Android Soft Keyboard в диалоговом окне?

В моем приложении пользовательский диалог находится в классе BaseExpandableListAdapter. В диалоговом окне у меня есть два текста редактирования. Первое - это имя и его обязательное. А во-вторых, адрес необязателен. И две кнопки ОК и отмена. Когда Dialog показывает, я хочу показать клавиатуру с фокусом запроса для редактирования текстового имени. После нажатия кнопки "ОК" Soft Keyboard следует скрыть.

4b9b3361

Ответ 1

final Dialog dialog = new Dialog(_context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

dialog.setContentView(R.layout.prompts);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

final EditText name = (EditText) dialog.findViewById(R.id.name);
final EditText add = (EditText) dialog.findViewById(R.id.add);

Button btnok = (Button) dialog.findViewById(R.id.btn_ok);
Button btncancel = (Button) dialog.findViewById(R.id.btn_cancel);

 btnAddExpList.setOnClickListener(new OnClickListener() {
  @Override
   public void onClick(View v) {           dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);  
   }
 }

Ответ 2

при нажатии кнопки ok напишите нижеприведенный код: -

  final Dialog dialog=new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    final EditText text = (EditText) dialog.findViewById(R.id.nameField);

   Button mOkBtn=(Button)dialog.findViewById(R.id.okBtn);


    // if button is clicked, close the custom dialog
   mOkBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            InputMethodManager imm = (InputMethodManager)getSystemService(context.INPUT_METHOD_SERVICE);
           imm.hideSoftInputFromWindow(text.getWindowToken(), 0);
        }
    });

    dialog.show();

Определить контекст как контекст контекста = это.

Ответ 3

Используйте следующий код, чтобы скрыть клавиатуру

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Используйте следующий код для отображения клавиатуры

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Ответ 4

Используйте это в своей деятельности

@Override
    public boolean dispatchTouchEvent(MotionEvent event) {

        View v = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);

        if (v instanceof EditText) {
            View w = getCurrentFocus();
            int scrcoords[] = new int[2];
            w.getLocationOnScreen(scrcoords);
            float x = event.getRawX() + w.getLeft() - scrcoords[0];
            float y = event.getRawY() + w.getTop() - scrcoords[1];

            if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
            }
        }
    return ret;
    }

Ответ 5

Используйте эту функцию:

public void hideKeyboard() {
    if (getDialog().getCurrentFocus() != null) {
        InputMethodManager inputManager = (InputMethodManager) Objects.requireNonNull(getActivity()).getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

Я хочу, чтобы это было полезно

Ответ 6

Показать KeyBoard когда вы показываете Dialog и закрываете KeyBoard когда вы нажимаете кнопку OK, как KeyBoard ниже...

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getApplicationContext());
alertDialogBuilder.setTitle(getString(R.string.app_error) + ":" + errorCode);
alertDialogBuilder.setMessage("Message");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int id) {

          imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);       }
});

alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      @Override
      public void onClick(DialogInterface dialog, int id) {

      }
});

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

Ответ 7

  1. Когда Dialog показывает, я хочу показать клавиатуру с фокусом запроса для редактирования текстового имени.

Это легко, как вы сами это ответили. Добавьте <requestfocus/> в свой EditText через xml или editText.requestFocus(); через код, прежде чем вы откроете диалог.

  1. После нажатия кнопки "ОК" Soft Keyboard следует скрыть.

Это может быть достигнуто двумя способами, в зависимости от того, что вы делаете при нажатии кнопки OK.

а. Если вы android:windowSoftInputMode="stateHidden" новую активность - добавьте android:windowSoftInputMode="stateHidden" к этой активности в манифесте, поэтому каждый раз, когда активность начинается, клавиатура будет скрыта, если вы ее не назовете.

б. Если вы находитесь на одной странице - вызовите метод ниже.

    private void hideSoftKeyBoard() {
            try {
                // hides the soft keyboard when the drawer opens
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

В случае getCurrentFocus() getWindowToken() дает ошибку, затем передает любой вид (вы можете отслеживать это через блок catch try), где View может быть любым, Button, EditText и т.д. Вашей активности (myButton..getWindowToken()),

Ответ 8

Вот решение:

    private fun showCustomDialog() {

        // Normal dialog stuff
        // -----
        val builder = AlertDialog.Builder(activity as Context) 
        val customLayout = View.inflate(context, R.layout.dialog_layout, null)
        val editText: EditText = customLayout.findViewById(R.id.edit_text)
        // -----

        // Get a hold of the inpoutMethodManager here
        val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

        builder.setTitle(getText(R.string.dialog_title))
        builder.setView(customLayout)
        builder.setPositiveButton(getText(R.string.action_confirm)) { _, _ ->
            // Hide the soft keyboard here after the positive button onclick
            imm.hideSoftInputFromWindow(editText.windowToken, 0)
            /*
             * Do your logic here for the positive click
             * ....
             */
        }
        builder.setNegativeButton(getText(R.string.action_cancel)) { dialog, _ ->
            // Also hide the soft keyboard if the user clicked negative button
            imm.hideSoftInputFromWindow(editText.windowToken, 0)
            /*
             * Do your logic here for the negative click
             * ....
             */
            dialog.cancel()
        }
        // added not cancelable for the dialog since it might mess with the keyboard hiding
        builder.setCancelable(false)
        builder.show()

        // make sure you call this to request focus, or else the hiding might not work...
        editText.requestFocus()
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }

Ответ 9

Используй это.

protected void hideKeyboardDialog(Dialog dialog){
    View view = dialog.getView();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}