Android: Pokaż miękką klawiaturę automatycznie, gdy fokus jest na EditText

Wyświetlam pole wprowadzania za pomocą AlertDialog. EditText wewnątrz samego okna dialogowego jest automatycznie skupiona, gdy wywołuję AlertDialog.show(), ale miękka klawiatura nie jest wyświetlana automatycznie.

Jak sprawić, by miękka klawiatura wyświetlała się automatycznie po wyświetleniu okna dialogowego? (i nie ma fizycznej/sprzętowej klawiatury). Podobnie jak po naciśnięciu przycisku Szukaj, aby wywołać globalne wyszukiwanie, miękka klawiatura jest automatycznie wyświetlana.

Author: Mat Nadrofsky, 2010-03-08

24 answers

Możesz utworzyć focus listener na {[1] } na AlertDialog, a następnie pobrać AlertDialog ' S Window. Stamtąd możesz zrobić soft keyboard show przez wywołanie setSoftInputMode.

final AlertDialog dialog = ...;

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});
 279
Author: Randy Sugianto 'Yuku',
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
2010-03-10 15:54:14

Do pokazania użycia klawiatury:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

Do ukrywania użycia klawiatury:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 
 200
Author: horkavlna,
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-06-22 11:33:57

Możesz poprosić o miękką klawiaturę zaraz po utworzeniu okna dialogowego (test na SDK - r20)

// create dialog
final AlertDialog dialog = ...; 

// request keyboard   
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
 98
Author: Bao Le,
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-12 04:59:32

Miałem ten sam problem i rozwiązałem go za pomocą poniższego kodu. Nie jestem pewien, jak będzie się zachowywał na telefonie z klawiaturą sprzętową.

// TextEdit
final EditText textEdit = new EditText(this);

// Builder
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter text");
alert.setView(textEdit);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String text = textEdit.getText().toString();
        finish();
    }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
});

// Dialog
AlertDialog dialog = alert.create();
dialog.setOnShowListener(new OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
    }
});

dialog.show();
 24
Author: tidbeck,
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
2011-10-11 09:51:05

Znalazłem ten przykład http://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html. dodaj poniższy kod tuż przed alert.show().

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
 21
Author: Jurie Otto,
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-02-28 06:41:27
<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

Lub

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
 15
Author: ahtartam,
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-09-05 22:55:20

Fragmenty kodu z innych odpowiedzi działają, ale nie zawsze jest oczywiste, gdzie je umieścić w kodzie, zwłaszcza jeśli używasz AlertDialog.Builder i postępujesz zgodnie z oficjalnym samouczkiem dialogowym , ponieważ nie używa final AlertDialog ... ani alertDialog.show().

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

Jest preferowane

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

Ponieważ SOFT_INPUT_STATE_ALWAYS_VISIBLE ukryje klawiaturę, jeśli fokus przełączy się z EditText, gdzie SHOW_FORCED będzie wyświetlać klawiaturę do momentu jej jawnego odrzucenia, nawet jeśli użytkownik wraca do ekranu głównego lub wyświetla najnowsze aplikacje.

Poniżej znajduje się kod roboczy dla AlertDialog utworzonego przy użyciu niestandardowego układu z EditText zdefiniowanym w XML. Ustawia również klawiaturę na Klawisz " go " i pozwala na uruchomienie przycisku dodatniego.

Alert_dialog.xml:

<RelativeLayout
android:id="@+id/dialogRelativeLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <!-- android:imeOptions="actionGo" sets the keyboard to have a "go" key instead of a "new line" key. -->
    <!-- android:inputType="textUri" disables spell check in the EditText and changes the "go" key from a check mark to an arrow. -->
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:imeOptions="actionGo"
        android:inputType="textUri"/>

</RelativeLayout>

AlertDialog.java:

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

public class CreateDialog extends AppCompatDialogFragment {
    // The public interface is used to send information back to the activity that called CreateDialog.
    public interface CreateDialogListener {
        void onCreateDialogCancel(DialogFragment dialog);    
        void onCreateDialogOK(DialogFragment dialog);
    }

    CreateDialogListener mListener;

    // Check to make sure that the activity that called CreateDialog implements both listeners.
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (CreateDialogListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement CreateDialogListener.");
        }
    }

    // onCreateDialog requires @NonNull.
    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        LayoutInflater customDialogInflater = getActivity().getLayoutInflater();

        // Setup dialogBuilder.
        alertDialogBuilder.setTitle(R.string.title);
        alertDialogBuilder.setView(customDialogInflater.inflate(R.layout.alert_dialog, null));
        alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogCancel(CreateDialog.this);
            }
        });
        alertDialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogOK(CreateDialog.this);
            }
        });

        // Assign the resulting built dialog to an AlertDialog.
        final AlertDialog alertDialog = alertDialogBuilder.create();

        // Show the keyboard when the dialog is displayed on the screen.
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        // We need to show alertDialog before we can setOnKeyListener below.
        alertDialog.show();

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

        // Allow the "enter" key on the keyboard to execute "OK".
        editText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button, select the PositiveButton "OK".
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Trigger the create listener.
                    mListener.onCreateDialogOK(CreateDialog.this);

                    // Manually dismiss alertDialog.
                    alertDialog.dismiss();

                    // Consume the event.
                    return true;
                } else {
                    // If any other key was pressed, do not consume the event.
                    return false;
                }
            }
        });

        // onCreateDialog requires the return of an AlertDialog.
        return alertDialog;
    }
}
 13
Author: Soren Stoutner,
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-12-17 17:21:20

Spójrz na to dyskusja, która zajmuje się ręcznym ukrywaniem i pokazywaniem IME. Jednak mam wrażenie, że jeśli skupiony EditText nie podnosi IME, to dlatego, że wywołujesz AlertDialog.show() w swoim OnCreate() lub inną metodę, która jest wywoływana przed wyświetlaniem ekranu. Przeniesienie go do OnPostResume() powinno to naprawić.

 7
Author: jqpubliq,
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
2010-03-08 19:13:13

Pozwól, że wskażę kilka dodatkowych informacji na temat rozwiązania Juku, ponieważ trudno mi to uruchomić! Jak uzyskać obiekt AlertDialog z mojego AlertDialog.Budowniczy? To wynik mojej alert.show() egzekucji:

final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
alert.setView(input);

// do what you need, like setting positive and negative buttons...

final AlertDialog dialog = alert.show();

input.setOnFocusChangeListener(new OnFocusChangeListener() {
   @Override
   public void onFocusChange(View v, boolean hasFocus) {
      if(hasFocus) {
         dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
      }
   }
});
 7
Author: user1344313,
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-08-25 14:00:47

Cóż, to jest dość stary post, wciąż jest coś do dodania.
są to 2 proste metody, które pomagają mi utrzymać klawiaturę pod kontrolą i działają po prostu idealnie:

Pokaż klawiaturę

public void showKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.showSoftInput(v, 0);
}

Ukryj klawiaturę

public void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
 7
Author: sberezin,
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-10-11 20:49:29

Tak, możesz zrobić z setOnFocusChangeListener to ci pomoże.

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});
 5
Author: Sachin Surjan,
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-06-21 12:04:18

Jeśli ktoś dostaje:

Nie można wykonać statycznego odniesienia do niestatycznej metody getSystemService (String) z Typu Activity

Spróbuj dodać kontekst do wywołania getSystemService.

Więc

InputMethodManager imm = 
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
 3
Author: Ryan Wittenburg,
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-06-09 19:59:35

Oryginalne pytanie dotyczy okien dialogowych, a mój EditText jest w regularnym widoku. W każdym razie, podejrzewam, że to powinno zadziałać dla większości z was. Więc oto, co działa dla mnie (wyżej sugerowana najwyżej oceniana metoda nie zrobiła dla mnie nic). Oto Niestandardowy EditView, który to robi (podklasowanie nie jest konieczne, ale uznałem to za wygodne dla moich celów, ponieważ chciałem również złapać ostrość, gdy widok staje się widoczny).

Jest to właściwie w dużej mierze to samo, co odpowiedź tidbecks. Właściwie to nie. zwróć uwagę na jego odpowiedź, ponieważ miał zero głosów. Potem miałem po prostu skomentować jego post, ale to byłoby zbyt długo, więc i tak skończyłem robić ten post. tidbeck wskazuje, że nie jest pewien, jak to działa z urządzeniami posiadającymi klawiatury. Mogę potwierdzić, że zachowanie wydaje się być dokładnie takie samo w obu przypadkach. To jest takie, że w trybie pionowym pojawia się klawiatura programowa, a w krajobrazie nie. wysuwanie fizycznej klawiatury czy nie robi żadnej różnicy na moim telefon.

Ponieważ, osobiście uważam zachowanie za trochę niezręczne, zdecydowałem się na użycie: InputMethodManager.SHOW_FORCED. To działa tak, jak chciałem. Klawiatura staje się widoczna niezależnie od orientacji, jednak przynajmniej na moim urządzeniu nie wyskakuje, jeśli klawiatura sprzętowa została wysuwana.

import android.app.Service;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class BringOutTheSoftInputOnFocusEditTextView extends EditText {

    protected InputMethodManager inputMethodManager;

    public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

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

    public BringOutTheSoftInputOnFocusEditTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        this.inputMethodManager = (InputMethodManager)getContext().getSystemService(Service.INPUT_METHOD_SERVICE);
        this.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    BringOutTheSoftInputOnFocusEditTextView.this.inputMethodManager.showSoftInput(BringOutTheSoftInputOnFocusEditTextView.this, InputMethodManager.SHOW_FORCED);
                }
            }
        });
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == View.VISIBLE) {
            BringOutTheSoftInputOnFocusEditTextView.this.requestFocus();
        }
    }

}
 1
Author: Timo,
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
2014-06-11 08:52:52

Problem polega na tym, że ponieważ miejsce, w którym wpisujesz tekst, jest początkowo ukryte (lub zagnieżdżone lub coś takiego), AlertDialog automatycznie ustawia flagę WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM lub WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, aby rzeczy nie wyzwalały miękkiego wejścia, aby się pokazać.

Aby to naprawić należy dodać:

(...)
// Create the dialog and show it
Dialog dialog = builder.create()
dialog.show();

// After show (this is important specially if you have a list, a pager or other view that uses a adapter), clear the flags and set the soft input mode
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
 1
Author: Magritte,
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
2014-12-02 05:04:31

Spróbuj użyć:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
 1
Author: ungalcrys,
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-02-19 00:43:58

Aby pokazać klawiaturę, dla mnie musiałem wykonać następujące

Android TextField: Ustaw focus + soft input programowo

Zasadniczo rozwiązanie jest następujące

@Override
public void onResume() {
    super.onResume();
    //passwordInput.requestFocus(); <-- that doesn't work
    passwordInput.postDelayed(new ShowKeyboard(), 325); //250 sometimes doesn't run if returning from LockScreen
}

Gdzie ShowKeyboard jest

private class ShowKeyboard implements Runnable {
    @Override
    public void run() {
        passwordInput.setFocusableInTouchMode(true);
        //passwordInput.requestFocusFromTouch(); //this gives touch event to launcher in background -_-
        passwordInput.requestFocus();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
    }
}

Po udanym wejściu, upewniam się również, że ukrywam klawiaturę

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getView().getWindowToken(), 0);
 1
Author: EpicPandaForce,
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-13 22:31:26

To jest dobra próbka dla ciebie:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollID"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="true"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:weightSum="1" >

        <EditText
            android:id="@+id/txtInpuConversation"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:hint="@string/edt_Conversation" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/btnSend"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/btn_Conversation" />
    </LinearLayout>

</LinearLayout>
 0
Author: A.A,
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
2014-08-20 10:53:29

Dlaczego ta odpowiedź - bo powyższe rozwiązanie pokaże twoją klawiaturę, ale nie zniknie, jeśli klikniesz w inne miejsce EditText. Musisz więc zrobić coś, aby klawisz zniknął, gdy EditText straci ostrość.

Możesz to osiągnąć wykonując następujące kroki:

  1. Aby Widok nadrzędny (Widok zawartości Twojej aktywności) był klikalny i ustawialny, dodając następujące atrybuty

        android:clickable="true" 
        android:focusableInTouchMode="true" 
    
  2. Zaimplementuj hideKeyboard() metoda

        public void hideKeyboard(View view) {
            InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY );
        }
    
  3. Na koniec ustaw onFocusChangeListener twojego edittext.

        edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
    
 0
Author: Darpan,
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
2014-09-10 11:59:32

To trochę skomplikowane. Zrobiłem to w ten sposób i to zadziałało.

1.At pierwsze wywołanie, aby ukryć miękkie wejście z okna. Spowoduje to ukrycie miękkiego wejścia, jeśli miękka klawiatura jest widoczna lub nie zrobi nic, jeśli nie jest.

2.Pokaż okno dialogowe

3.Następnie po prostu zadzwoń, aby przełączyć miękkie wejście.

Kod:

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWind‌​owToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);
 0
Author: FRR,
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-02-26 17:46:31

Spróbuj tego

SomeUtils.java

public static void showKeyboard(Activity activity, boolean show) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);

    if(show)
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
    else
        inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
}
 0
Author: GameBug,
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-08-29 23:54:23

Umieść te metody w swojej klasie Util i używaj ich wszędzie.

Kotlin

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
 0
Author: Khemraj,
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-10-01 10:02:05

As horkavlna wrote:

toggle

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

I Ukryj klawiaturę

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); 

Metody działają. Ale Pokaż warianty nie działają w moim przypadku. Więc w onCreate() wkładam hideKeyboard(editText); potem w onStart() piszę toggleKeyboard(editText); i w onStop() piszę hideKeyboard(editText);.

Istnieją trzy problemy:

1) gdy aplikacja uruchomi się z wyłączonym ekranem, ukryje klawiaturę,

2) za każdym razem, gdy włączysz ekran, wyświetli się klawiatura,

3) Po zakończeniu aplikacji można zobaczyć klawiaturę na ekranie głównym Androida.

Po kilku testach usunąłem te metody i w AndroidManifest W activity tagi napisał android:windowSoftInputMode="stateVisible" lub android:windowSoftInputMode="stateAlwaysHidden".

 0
Author: CoolMind,
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-10-05 14:22:14

Stworzyłem ładne funkcje rozszerzeń kotlin-esqe, aby każdy był zainteresowany

fun Activity.hideKeyBoard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

fun Activity.showKeyboard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
 0
Author: i am E,
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-10-07 21:29:51
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Wywołuję to w OnCreate (), aby wyświetlić klawiaturę automatycznie, gdy przyszedłem w aktywności.

 -1
Author: Raul Yang,
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-09-12 05:46:02