364

を使用して入力ボックスを表示していますAlertDialog。を呼び出すと、EditTextダイアログ内自体が自動的にフォーカスされますAlertDialog.show()が、ソフトキーボードは自動的に表示されません。

ダイアログが表示されたときにソフトキーボードを自動的に表示するにはどうすればよいですか?(そして、物理/ハードウェアキーボードはありません)。[検索]ボタンを押してグローバル検索を呼び出す場合と同様に、ソフトキーボードが自動的に表示されます。

4

29 に答える 29

315

にフォーカスリスナーを作成してEditTextからAlertDialog、を取得できAlertDialogますWindow。そこから、を呼び出すことでソフトキーボードを表示できます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);
        }
    }
});
于 2010-03-10T15:54:14.160 に答える
252

キーボードの使用法を示すために:

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

キーボードの使用を非表示にする場合:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 
于 2012-06-22T11:33:57.367 に答える
112

ダイアログを作成した直後にソフトキーボードをリクエストできます(SDKでテスト-r20)

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

// request keyboard   
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
于 2011-11-05T06:41:16.273 に答える
26

この例を見つけましたhttp://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html。の直前に次のコードを追加しますalert.show()

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
于 2012-02-28T06:06:14.097 に答える
25

私は同じ問題を抱えていて、次のコードでそれを解決しました。ハードウェアキーボードを備えた電話でどのように動作するかわかりません。

// 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();
于 2011-10-11T09:51:05.897 に答える
20
<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

また

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
于 2013-09-05T22:55:20.553 に答える
16

他の回答からのコードのスニペットは機能しますが、コード内のどこに配置するかが常に明確であるとは限りません。特に、またはを使用していないため、公式のダイアログチュートリアルAlertDialog.Builderに従っている場合はそうです。final AlertDialog ...alertDialog.show()

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

に好ましい

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

SOFT_INPUT_STATE_ALWAYS_VISIBLEは、フォーカスがEditTextから離れるとキーボードを非表示にするため、SHOW_FORCEDは、ユーザーがホーム画面に戻ったり最近のアプリを表示したりしても、明示的に閉じられるまでキーボードを表示したままにします。

以下は、XMLで定義されたEditTextを使用してカスタムレイアウトを使用して作成されたAlertDialogの作業コードです。また、キーボードに「移動」キーを設定し、ポジティブボタンをトリガーできるようにします。

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;
    }
}
于 2015-12-17T05:07:11.080 に答える
13

私はこの質問が古いことを知っています。拡張機能を使用することは、編集テキスト用のキーボードを表示するためのより美しい方法だと思います。

これが、エディットテキストのキーボードを表示するために使用する方法です。

kotlinコード: 呼び出す必要がありますedittext.showKeyboard()

fun EditText.showKeyboard() {
  post {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
  }
}

Javaコード:

public static void showKeyboard(EditText editText) {
    editText.post(new Runnable() {
      @Override
      public void run() {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) editText.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
      }
    });
  }
于 2019-07-06T04:52:25.457 に答える
11

まあ、これはかなり古い投稿ですが、まだ追加するものがあります。
これらは、キーボードを制御し続けるのに役立つ2つの簡単な方法であり、完璧に機能します。

キーボードを表示

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

キーボードを隠す

public void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
于 2015-10-11T20:49:29.447 に答える
10

これを機能させるのは難しいと思ったので、yukuの解決策にいくつかの追加情報を指摘させてください!AlertDialog.BuilderからAlertDialogオブジェクトを取得するにはどうすればよいですか?まあ、それは私のalert.show()実行の結果です:

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);
      }
   }
});
于 2012-12-20T15:05:22.567 に答える
7

IMEの手動の非表示と表示を処理するこのディスカッションをご覧ください。ただし、フォーカスEditTextがIMEを表示しない場合は、画面が実際に表示される前に呼び出されるメソッドまたはその他のメソッドを呼び出しAlertDialog.show()ているためだと思います。OnCreate()に移動OnPostResume()すると、その場合は修正されるはずです。

于 2010-03-08T19:13:13.787 に答える
6

はい、あなたはそれでsetOnFocusChangeListenerあなたを助けることができます。

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);
        }
    }
});
于 2012-06-21T08:50:25.303 に答える
4

誰かが取得している場合:

タイプActivityから非静的メソッドgetSystemService(String)への静的参照を作成できません

getSystemService呼び出しにコンテキストを追加してみてください。

それで

InputMethodManager imm = 
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
于 2012-06-09T19:59:35.890 に答える
2

この行をマニフェストファイルに必要なアクティビティに追加するだけです。

android:windowSoftInputMode="stateVisible"

于 2020-10-01T05:08:07.327 に答える
1

元の質問はダイアログに関するもので、私のEditTextは通常のビューにあります。とにかく、これはあなたのほとんどにとってもうまくいくはずだと思います。だからここに私のために働くものがあります(上記の提案された最高評価の方法は私にとって何もしませんでした)。これを行うカスタムEditViewを次に示します(サブクラス化は必要ありませんが、ビューが表示されたときにフォーカスを取得したかったので、目的に便利であることがわかりました)。

これは実際にはtidbecksの答えとほぼ同じです。投票数がゼロだったので、私は実際には彼の答えにまったく気づきませんでした。それから私は彼の投稿にコメントしようとしていましたが、それは長すぎたので、とにかくこの投稿をやめました。tidbeckは、キーボードを備えたデバイスでどのように機能するかわからないと指摘しています。どちらの場合も、動作はまったく同じように見えることが確認できます。これは、ポートレートモードではソフトウェアキーボードがポップアップし、ランドスケープモードではポップアップしないというものです。物理的なキーボードをスライドさせてもしなくても、私の電話には何の違いもありません。

なぜなら、私が個人的に使用することを選択した動作が少し厄介であることに気付いたからですInputMethodManager.SHOW_FORCED。これは私が望んでいたように機能します。キーボードは向きに関係なく表示されますが、少なくとも私のデバイスでは、ハードウェアキーボードをスライドさせてもポップアップしません。

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

}
于 2011-10-25T18:26:59.870 に答える
1

問題は、テキストを入力する場所が最初は非表示になっている(またはネストされているなど)ため、AlertDialogが自動的にフラグを設定するWindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IMWindowManager.LayoutParams.FLAG_NOT_FOCUSABLE、ソフト入力が表示されないようにすることです。

これを修正する方法は、以下を追加することです。

(...)
// 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);
于 2014-12-02T05:04:31.083 に答える
1

試して使用してください:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
于 2015-02-19T00:43:58.497 に答える
1

キーボードを表示するには、私にとって、次のことをしなければなりませんでした

Android TextField:プログラムでフォーカスとソフト入力を設定します

基本的に解決策は次のとおりです

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

どこShowKeyboardにありますか

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

入力が成功したら、キーボードを非表示にすることも確認します

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getView().getWindowToken(), 0);
于 2015-03-24T10:41:06.013 に答える
1
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

onCreate()でこれを呼び出して、アクティビティに参加したときにキーボードを自動的に表示します。

于 2018-09-12T02:31:06.107 に答える
1

これらのメソッドをUtilクラスに入れて、どこでも使用できます。

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);
}
于 2018-10-01T10:02:05.247 に答える
1

誰かが興味を持っている場合に備えて、素敵なkotlin-esqe拡張関数を作成しました

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)
}
于 2018-10-07T21:29:51.913 に答える
1

多くのことを試しましたが、これが私のために働いたものです(kotlin):

        val dialog = builder.create()
        dialog.setOnShowListener {
            nameEditText.requestFocus()
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }

        dialog.setOnDismissListener {
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }

        dialog.show()
于 2019-05-29T08:42:55.190 に答える
0

これはあなたにとって良いサンプルです:

<?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>
于 2014-08-20T10:53:29.997 に答える
0

なぜこの答え-上記の解決策はキーボードを表示しますが、それ以外の場所をクリックしても消えないためですEditText。したがって、フォーカスを失ったときにキーボードが消えるようにするために何かをする必要がありEditTextます。

これは、次の手順で実行できます。

  1. 次の属性を追加して、親ビュー(アクティビティのコンテンツビュー)をクリックおよびフォーカス可能にします

        android:clickable="true" 
        android:focusableInTouchMode="true" 
    
  2. HideKeyboard()メソッドを実装します

        public void hideKeyboard(View view) {
            InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY );
        }
    
  3. 最後に、エディットテキストのonFocusChangeListenerを設定します。

        edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
    
于 2014-09-10T11:59:32.760 に答える
0

これは少し注意が必要です。私はこのようにしました、そしてそれは働きました。

1.最初に呼び出して、ウィンドウからソフト入力を非表示にします。これにより、ソフトキーボードが表示されている場合はソフト入力が非表示になり、表示されていない場合は何も実行されません。

2.ダイアログを表示する

3.次に、を呼び出してソフト入力を切り替えます。

コード:

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);
于 2015-02-26T17:46:31.933 に答える
0

これを試して

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);
}
于 2018-08-29T23:54:23.410 に答える
0

https://stackoverflow.com/a/39144104/2914140を見て、私は少し単純化しました:

// In onCreateView():
view.edit_text.run {
    requestFocus()
    post { showKeyboard(this) }
}

fun showKeyboard(view: View) {
    val imm = view.context.getSystemService(
        Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    imm?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

https://stackoverflow.com/a/11155404/2914140よりも優れています:

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

ホームボタンを押してホーム画面に移動すると、キーボードは開いたままになるためです。

于 2018-10-05T10:39:39.640 に答える
0

ソフトキーボードをEditText内側から表示する場合のこの問題は、表示後に適用されたため、AlertDialogおそらくにあります。APIのすべてのバージョンに当てはまるかどうかはわかりませんが、ソリューションにはAPIレベル21が付属していると思います。これは、の前に呼び出す必要があるためです。AlertDialog.show()EditTextAlertDialogAlertDialog.create()AlertDialog.show()

これがこの場合の私の最善の解決策です。まず、どこかに作成します。

    private int showKeyboard(View view) {
        final InputMethodManager inputManager = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            boolean isShown = inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // flag=InputMethodManager.SHOW_IMPLICIT ili =
            return (isShown) ? 1: -1;
        }
        return 0;
    }

次に、AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());続行した後:

    EditText editText = new EditText(requireContext());
    builder.setView(editText);
    // ... put positive-negative buttons, and etc ...
    AlertDialog dialog = builder.create(); // Create dialog from builder
    dialog.setCancelable(false); // If you need
    Handler handler = new Handler();
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) { // 1. When a dialog is displayed
            editText.requestFocus();
            Runnable runnable = new Runnable() { // create one runnable
                int counter = 0;
                public void run() {
                    int status = showKeyboard(editText); // 2. Call func.above for keyboard, but...
                    if(status == -1 && counter < 10){ handler.postDelayed(this, 100); counter ++; } // ...if it inst shown call again after 100ms
                }
            };
            runnable.run(); // Execute runnable first time here
        }
    });
    dialog.show();

忘れないimport android.os.Handler;でくださいなど;-)

ありがとうVote Up

于 2021-04-25T19:36:33.077 に答える
0

私の方法はAndroid11以降の新しい方法を使用し、古いバージョンもサポートしています。

fun Fragment.showKeyboard() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        ViewCompat.getWindowInsetsController(requireView())?.show(WindowInsetsCompat.Type.ime())
    } else {
        val focusedView = view?.findFocus() ?: view?.apply { requestFocus() }
        val imm = (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
        val isShowSucceeded = imm.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
        if(!isShowSucceeded) {
            imm.toggleSoftInputFromWindow(
                view?.windowToken, 0, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }
}

}

于 2022-01-23T13:08:38.023 に答える