Disable Software Keyboard in Android until EditText is chosen

前端 未结 3 938
悲&欢浪女
悲&欢浪女 2021-02-06 19:28

how can I prevent the software keyboard to disappear until a specific EditText is choosen? I have several EditTexts in my Layout when it is opened the first is automatically sel

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 20:25

    I try this to make the keyboard appear only when user clicks on edittext, all the other solutions don't work for me. It's a bit weird but from now it's the solution I found. You must put this events in all edittexts on the layout.

    OnClickListener click = new OnClickListener() {
        @Override
        public void onClick(View v) {
            v.setFocusableInTouchMode(true);
            v.requestFocusFromTouch();
        }
    };
    OnFocusChangeListener focus = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
                v.setFocusableInTouchMode(false);
            }
        }
    };
    

    Like this:

    EditText text = (EditText) getActivity().findViewById(R.id.myText);
    text.setText("Some text");
    text.setFocusableInTouchMode(false);
    text.setOnClickListener(click); 
    text.setOnFocusChangeListener(focus);
    

    EDIT:

    I just make a custom edit text to make easy to use in my project, hope it was usefull.

    public class EditTextKeyboardSafe extends EditText {
        public EditTextKeyboardSafe(Context context) {
            super(context);
            initClass();
        }
    
        public EditTextKeyboardSafe(Context context, AttributeSet attrs,
                int defStyle) {
            super(context, attrs, defStyle);
            initClass();
        }
    
        public EditTextKeyboardSafe(Context context, AttributeSet attrs) {
            super(context, attrs);
            initClass();
        }
    
        private void initClass() {
            this.setFocusableInTouchMode(false);
            this.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setFocusableInTouchMode(true);
                    v.requestFocusFromTouch();
                }
            });
            this.setOnFocusChangeListener(new OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (!hasFocus) {
                        v.setFocusableInTouchMode(false);
                    }
                }
            });
        }
    
    }
    

提交回复
热议问题