簡體   English   中英

隱藏鍵盤不適用於片段上的自定義對話框

[英]Hide keyboard not working with custom dialog on fragment

我有一個自定義對話框。 當對話框出現並且編輯字段獲得焦點時,數字鍵盤會自動出現。 但是當我點擊對話框周圍的灰色空間時,對話框本身消失了,但鍵盤仍然打開。 我試過關閉/隱藏 android 軟鍵盤,但它不起作用。

我的代碼

private Button mSearchBtn;
private EditText mEditText;
private DialogUserSearchPresenter mPresenter;

public DialogUserSearch(@NonNull Context context) {
    super(context);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.dialog_search);
    mPresenter = new DialogUserSearchPresenter(new MainInteractor(new UserRepository(new Prefs(getContext())), new HotUsersRepository(new Prefs(getContext())), new SystemRepository(new Prefs(getContext()))));
    mEditText = (EditText) findViewById(R.id.dialog_search_edit);
    mEditText.requestFocus();
    InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    mSearchBtn = (Button) findViewById(R.id.dialog_search_button);
    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mEditText.getText().length() == 10) {
                mPresenter.searchUser(mEditText.getText().toString().trim());
                closeKeyboard();
            } else {
                Toast.makeText(getContext(), getContext().getString(R.string.dialog_search_quantity_error),
                        Toast.LENGTH_LONG).show();
            }
        }
    });
}

@Override
protected void onStop() {
    super.onStop();
    closeKeyboard();
}



private void closeKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) getContext().getSystemService(getContext().INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

1)你可以試試這個:

private void closeKeyboard(View view) {
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

這樣調用:

closeKeyboard(mEditText);

我試過了

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM