Wyłącz klawiaturę w EditText

Robię Kalkulator. Więc stworzyłem własne Buttons z liczbami i funkcjami. Wyrażenie, które należy obliczyć, jest w EditText, ponieważ chcę, aby użytkownicy mogli dodawać liczby lub funkcje również w środku wyrażenia, więc z EditText Mam cursor. Ale chcę wyłączyć Keyboard, gdy użytkownicy klikną na EditText. Znalazłem ten przykład, że jest ok dla Android 2.3, ale z ICS wyłącz Keyboard, a także kursor.

public class NoImeEditText extends EditText {

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

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

A potem używam tego NoImeEditText w moim XML plik

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

Jak mogę zrobić kompatybilny ten EditText z ICS??? Dzięki.

Author: Darshan Rivka Whittle, 2012-05-17

13 answers

Tutaj jest strona, która da ci to, czego potrzebujesz

Jako podsumowanie, zawiera linki do InputMethodManager i View od deweloperów Androida. Będzie odnosić się do getWindowToken wewnątrz View i hideSoftInputFromWindow() dla InputMethodManager

Lepsza odpowiedź jest podana w linku, mam nadzieję, że to pomoże.

Oto przykład użycia zdarzenia 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
}
};

Oto kolejny przykład z tej samej strony. To twierdzi, że działa, ale wydaje się złym pomysłem, ponieważ Twój EditBox jest NULL, będzie nie bądź już redaktorem:

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
}
});

Mam nadzieję, że to wskaże ci właściwy kierunek

 35
Author: Hip Hip Array,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-17 13:28:11

Poniżej znajduje się zarówno API > = 11, jak i API

/**
 * 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);
    }
}
 56
Author: Aleksey Malevaniy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-22 04:27:30

Try: android:editable="false" or android:inputType="none"

 20
Author: K_Anas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-17 14:40:14

Możesz również użyć setShowSoftInputOnFocus (boolean) bezpośrednio na API 21+lub poprzez refleksję na API 14+:

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
    }
}
 10
Author: kuelye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-11 08:40:06

Wyłącz klawiaturę (API 11 do current)

Jest to najlepsza odpowiedź jaką znalazłem do tej pory, aby wyłączyć klawiaturę (i widziałem wiele z nich).

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

Nie ma potrzeby używania reflection ani ustawiania InputType Na null.

Włącz ponownie klawiaturę

Oto jak w razie potrzeby ponownie włączyć klawiaturę.

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);
}

Zobacz to pytanie, dlaczego skomplikowana wersja pre API 21 jest potrzebna do cofnięcia setTextIsSelectable(true):

Ta odpowiedź musi zostać dokładniej przetestowana.

Przetestowałem setShowSoftInputOnFocus na wyższych urządzeniach API, ale po komentarzu @androiddeveloper poniżej widzę, że trzeba to dokładniej przetestować.

Oto kod do wycinania i wklejania, który pomoże przetestować tę odpowiedź. Jeśli możesz potwierdzić, że działa lub nie działa dla API od 11 do 20, zostaw komentarz. Nie mam żadnych urządzeń API 11-20 i mój emulator ma problemy.

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>

główna aktywność.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);
        }
    }
}
 10
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-24 09:49:08
// 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);
 6
Author: Abel Terefe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-12 12:52:10

Zbieranie rozwiązań z wielu miejsc tutaj na StackOverflow, myślę, że następny podsumowuje to:

Jeśli nie potrzebujesz, aby klawiatura była pokazywana w dowolnym miejscu Twojej aktywności, możesz po prostu użyć kolejnych flag, które są używane w oknach dialogowych (pobrane z proszę.) :

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

Jeśli nie chcesz go tylko dla określonego EditText, możesz użyć tego (otrzymanego z tutaj) :

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;
}

Lub to (wzięte z proszę.) :

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
           editText.setShowSoftInputOnFocus(false);
       else
           editText.setTextIsSelectable(true); 
 6
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-24 07:27:24

Znalazłem takie rozwiązanie, które działa dla mnie. Po kliknięciu na EditText umieszcza również kursor we właściwej pozycji.

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;
        }
    });
 5
Author: Vijay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-19 16:21:33

Po prostu ustaw:

 NoImeEditText.setInputType(0);

Lub w konstruktorze:

   public NoImeEditText(Context context, AttributeSet attrs) { 
          super(context, attrs);   
          setInputType(0);
       } 
 4
Author: Alex Kucherenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-17 13:35:17

Dodaj poniższe właściwości do kontrolera Edittext w pliku układu

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

Używam tego rozwiązania od jakiegoś czasu i działa dobrze dla mnie.

 4
Author: Nishara MJ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-27 08:09:01

Aby dodać do rozwiązania Alexa Kucherenko: problem z znikaniem kursora po wywołaniu {[1] } jest spowodowany błędem frameworku na ICS (i JB).

Błąd jest udokumentowany tutaj: https://code.google.com/p/android/issues/detail?id=27609 .

Aby to obejść, zadzwoń setRawInputType(InputType.TYPE_CLASS_TEXT) zaraz po wywołaniu setInputType.

Aby zatrzymać pojawianie się klawiatury, wystarczy przesłać OnTouchListener EditText i zwrócić true (Połykanie zdarzenia touch):

ed.setOnTouchListener(new OnTouchListener() {

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

                return true;
            }
        });

Przyczyny kursor pojawiający się na urządzeniach GB, a nie na ICS+ sprawił, że przez kilka godzin wyrywałem sobie włosy, więc mam nadzieję, że zaoszczędzi to komuś czasu.

 3
Author: Jay Sidri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-08 14:07:56

To mi pomogło. Najpierw dodaj to android:windowSoftInputMode="stateHidden" do pliku manifestu androida, pod swoją aktywnością. jak poniżej:

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

Następnie w metodzie OnCreate swojej aktywności Dodaj kod foloowing:

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;
    }
});

Następnie, jeśli chcesz, aby wskaźnik był widoczny, dodaj go do swojego xml android:textIsSelectable="true".

Spowoduje to, że wskaźnik będzie widoczny. W ten sposób klawiatura nie pojawi się po rozpoczęciu aktywności, a także będzie ukryta po kliknięciu na edittext.

 1
Author: Jerin A Mathews,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-24 15:37:34

Po prostu umieść tę linię wewnątrz tagu activity w manifeście android:windowSoftInputMode= "stateHidden"

 1
Author: mahmoud alaa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-03 11:07:48