IT TIP

EditText에서 키보드 비활성화

itqueen 2020. 11. 25. 21:49
반응형

EditText에서 키보드 비활성화


계산기를하고 있어요. 그래서 저는 Buttons숫자와 함수 로 나만의 것을 만들었습니다 . 계산 해야하는 EditText식은에 있습니다. 사용자가 식 중간에 숫자 나 함수를 추가 할 수 있기 때문에 . 하지만 사용자가 . 이 예제는 괜찮지 커서와 커서 비활성화했습니다 .EditTextcursorKeyboardEditTextAndroid 2.3ICSKeyboard

public class NoImeEditText extends EditText {

   public NoImeEditText(Context context, AttributeSet attrs) { 
      super(context, attrs);     
   }   

   @Override      
   public boolean onCheckIsTextEditor() {   
       return false;     
   }         
}

그리고 이것을 NoImeEditTextXML파일에 사용 합니다.

<com.my.package.NoImeEditText
      android:id="@+id/etMy"
 ....  
/>

이 EditText를 ICS와 호환되도록하려면 어떻게해야합니까 ??? 감사.


다음 은 필요한 것을 제공하는 웹 사이트입니다.

요약하면 Android 개발자 InputMethodManager와의 링크를 제공합니다 View. 그것은에 참조합니다 getWindowToken내부 ViewhideSoftInputFromWindow()대한InputMethodManager

더 나은 답변이 링크에 나와 있습니다. 도움이되기를 바랍니다.

다음은 onTouch 이벤트를 사용하는 예입니다.

editText_input_field.setOnTouchListener(otl);

private OnTouchListener otl = new OnTouchListener() {
  public boolean onTouch (View v, MotionEvent event) {
        return true; // the listener has consumed the event
  }
};

다음은 동일한 웹 사이트의 또 다른 예입니다. 이것은 작동한다고 주장하지만 EditBox가 NULL이기 때문에 더 이상 편집기가 아니기 때문에 나쁜 생각처럼 보입니다.

MyEditor.setOnTouchListener(new OnTouchListener(){

  @Override
  public boolean onTouch(View v, MotionEvent event) {
    int inType = MyEditor.getInputType(); // backup the input type
    MyEditor.setInputType(InputType.TYPE_NULL); // disable soft input
    MyEditor.onTouchEvent(event); // call native handler
    MyEditor.setInputType(inType); // restore input type
    return true; // consume touch even
  }
});

이것이 올바른 방향을 가리 키기를 바랍니다.


아래 코드는 API> = 11 및 API <11에 대한 것입니다. 커서는 계속 사용할 수 있습니다.

/**
 * Disable soft keyboard from appearing, use in conjunction with android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
 * @param editText
 */
public static void disableSoftInputFromAppearing(EditText editText) {
    if (Build.VERSION.SDK_INT >= 11) {
        editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
        editText.setTextIsSelectable(true);
    } else {
        editText.setRawInputType(InputType.TYPE_NULL);
        editText.setFocusable(true);
    }
}

시도 : android:editable="false"또는android:inputType="none"


API 21+에서 직접 또는 API 14+에서 리플렉션을 통해 setShowSoftInputOnFocus (boolean)를 사용할 수도 있습니다 .

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    editText.setShowSoftInputOnFocus(false);
} else {
    try {
        final Method method = EditText.class.getMethod(
                "setShowSoftInputOnFocus"
                , new Class[]{boolean.class});
        method.setAccessible(true);
        method.invoke(editText, false);
    } catch (Exception e) {
        // ignore
    }
}

키보드 비활성화 (API 11 to current)

이것은 키보드를 비활성화하기 위해 지금까지 찾은 최고의 답변입니다 (그리고 많은 것을 보았습니다).

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
    editText.setShowSoftInputOnFocus(false);
} else { // API 11-20
    editText.setTextIsSelectable(true);
}

리플렉션을 사용하거나 InputType를 null로 설정할 필요가 없습니다 .

키보드 다시 활성화

필요한 경우 키보드를 다시 활성화하는 방법은 다음과 같습니다.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
    editText.setShowSoftInputOnFocus(true);
} else { // API 11-20
    editText.setTextIsSelectable(false);
    editText.setFocusable(true);
    editText.setFocusableInTouchMode(true);
    editText.setClickable(true);
    editText.setLongClickable(true);
    editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
    editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
}

실행 취소를 위해 복잡한 API 21 이전 버전이 필요한 이유는이 Q & A를 참조하세요 setTextIsSelectable(true).

이 답변은 더 철저하게 테스트되어야합니다.

나는 setShowSoftInputOnFocus더 높은 API 장치에서 테스트 했지만 아래 @androiddeveloper의 의견 후에 이것이 더 철저히 테스트되어야 함을 알았습니다.

이 답변을 테스트하는 데 도움이되는 잘라 내기 및 붙여 넣기 코드가 있습니다. API 11 ~ 20에서 작동하는지 여부를 확인할 수 있으면 의견을 남겨주세요. API 11-20 장치가없고 에뮬레이터에 문제가 있습니다.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    android:background="@android:color/white">

    <EditText
        android:id="@+id/editText"
        android:textColor="@android:color/black"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:text="enable keyboard"
        android:onClick="enableButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:text="disable keyboard"
        android:onClick="disableButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);
    }

    // when keyboard is hidden it should appear when editText is clicked
    public void enableButtonClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
            editText.setShowSoftInputOnFocus(true);
        } else { // API 11-20
            editText.setTextIsSelectable(false);
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.setClickable(true);
            editText.setLongClickable(true);
            editText.setMovementMethod(ArrowKeyMovementMethod.getInstance());
            editText.setText(editText.getText(), TextView.BufferType.SPANNABLE);
        }
    }

    // when keyboard is hidden it shouldn't respond when editText is clicked
    public void disableButtonClick(View view) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // API 21
            editText.setShowSoftInputOnFocus(false);
        } else { // API 11-20
            editText.setTextIsSelectable(true);
        }
    }
}

레이아웃 파일의 Edittext 컨트롤러에 아래 속성을 추가합니다.

<Edittext
   android:focusableInTouchMode="true"
   android:cursorVisible="false"
   android:focusable="false"  />

나는이 솔루션을 오랫동안 사용해 왔으며 잘 작동합니다.


나는 나를 위해 일하는이 솔루션을 찾았습니다. 또한 EditText를 클릭하면 올바른 위치에 커서를 놓습니다.

EditText editText = (EditText)findViewById(R.id.edit_mine);
// set OnTouchListener to consume the touch event
editText.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            v.onTouchEvent(event);   // handle the event first
            InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null) {
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  // hide the soft keyboard 
            }                
            return true;
        }
    });

여기 StackOverflow의 여러 장소에서 솔루션을 수집하면 다음 항목이 요약한다고 생각합니다.

활동의 어느 곳에도 키보드를 표시 할 필요가없는 경우 대화 상자에 사용되는 다음 플래그를 사용하면됩니다 ( 여기 에서 가져옴 ).

    getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

If you don't want it only for a specific EditText, you can use this (got from here) :

public static boolean disableKeyboardForEditText(@NonNull EditText editText) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        editText.setShowSoftInputOnFocus(false);
        return true;
    }
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
        try {
            final Method method = EditText.class.getMethod("setShowSoftInputOnFocus", new Class[]{boolean.class});
            method.setAccessible(true);
            method.invoke(editText, false);
            return true;
        } catch (Exception ignored) {
        }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
        try {
            Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
            method.setAccessible(true);
            method.invoke(editText, false);
            return true;
        } catch (Exception ignored) {
        }
    return false;
}

Or this (taken from here) :

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
           editText.setShowSoftInputOnFocus(false);
       else
           editText.setTextIsSelectable(true); 

// only if you completely want to disable keyboard for 
// that particular edit text
your_edit_text = (EditText) findViewById(R.id.editText_1);
your_edit_text.setInputType(InputType.TYPE_NULL);

Just set:

 NoImeEditText.setInputType(0);

or in the constructor:

   public NoImeEditText(Context context, AttributeSet attrs) { 
          super(context, attrs);   
          setInputType(0);
       } 

To add to Alex Kucherenko solution: the issue with the cursor getting disappearing after calling setInputType(0) is due to a framework bug on ICS (and JB).

The bug is documented here: https://code.google.com/p/android/issues/detail?id=27609.

To workaround this, call setRawInputType(InputType.TYPE_CLASS_TEXT) right after the setInputType call.

To stop the keyboard from appearing, just override OnTouchListener of the EditText and return true (swallowing the touch event):

ed.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return true;
            }
        });

The reasons for the cursor appearing on GB devices and not on ICS+ had me tearing my hair out for a couple of hours, so I hope this saves someone's time.


This worked for me. First add this android:windowSoftInputMode="stateHidden" in your android manifest file, under your activity. like below:

<activity ... android:windowSoftInputMode="stateHidden">

Then on onCreate method of youractivity, add the foloowing code:

EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethod!= null) {
            inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }                
        return true;
    }
});

Then if you want the pointer to be visible add this on your xml android:textIsSelectable="true".

This will make the pointer visible. In this way the keyboard will not popup when your activity starts and also will be hidden when you click on the edittext.


editText.setShowSoftInputOnFocus(false);

Just put this line inside the activity tag in manifest android:windowSoftInputMode="stateHidden"

참고URL : https://stackoverflow.com/questions/10636635/disable-keyboard-on-edittext

반응형