Android:焦点在EditText上时自动显示软键盘

Ran*_*ku' 328 keyboard android soft-keyboard android-edittext

我正在使用输入框AlertDialog.在EditText该对话框中本身自动对焦,当我打电话AlertDialog.show(),但软键盘未自动显示.

如何在显示对话框时自动显示软键盘?(并且没有物理/硬件键盘).与按下"搜索"按钮调用全局搜索的方式类似,将自动显示软键盘.

Ran*_*ku' 296

您可以在创建一个焦点侦听器EditTextAlertDialog,然后得到AlertDialogWindow.从那里你可以通过调用来制作软键盘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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

  • **我回顾上面的评论**我发现如果你无法正确关注,请查看你的XML!如果你在那里看到标签*<requestFocus> </ requestFocus>* - 将其删除.似乎标签会将焦点放在EditText上,然后您的侦听器将不会被触发,因为EditText已经具有焦点. (30认同)
  • 如果设备有硬件键盘,你怎么办?这似乎对这些用户来说很烦人. (11认同)
  • 我真的不明白为什么这不是SDK中的默认行为.如果需要文本输入的视图显示闪烁的光标,为什么有人不想看到键盘输入文本?对我而言,用户体验感觉如此错误 (7认同)
  • 我如何使用AlertDialog.Builder?... final AlertDialog.Builder alert = new AlertDialog.Builder(Main.this); (5认同)
  • @Stephen您可以使用`final AlertDialog dialog = builder.create()`然后在对话框中显示`show`而不是构建器来从构建器获取对话框. (5认同)
  • 对我不起作用 - Nexus S.在节目之前和之后尝试过(). (3认同)
  • @ChristianGarcia android 中内置的许多白痴之一。这个 SDK 充满了令人难以置信的错误。 (2认同)

小智 228

用于显示键盘用途:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
Run Code Online (Sandbox Code Playgroud)

隐藏键盘使用:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 
Run Code Online (Sandbox Code Playgroud)

  • 我建议改为使用SHOW_IMPLICIT标志,因为这意味着更改活动或应用程序将按预期自动隐藏键盘. (34认同)
  • @drspaceboo使用SHOW_IMPLICIT对我来说根本不起作用,我必须使用SHOW_FORCED,不知道为什么...... (6认同)
  • 当您想要显示/隐藏软键盘时,这种方法特别有效,因为您可以在VISIBLE和GONE之间切换布局中视图的可见性. (3认同)
  • 这个答案对我来说就像一个魅力...其他人没有:S (3认同)

Bao*_* Le 110

您可以在创建对话框后立即请求软键盘(在SDK上测试 - r20)

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

// request keyboard   
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Run Code Online (Sandbox Code Playgroud)

  • 最后一个真的有用!谢谢!! (7认同)

tid*_*eck 24

我有同样的问题,并用以下代码解决了它.我不确定它在具有硬件键盘的手机上的表现如何.

// 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();
Run Code Online (Sandbox Code Playgroud)


小智 23

我找到了这个例子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);
Run Code Online (Sandbox Code Playgroud)


小智 17

<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>
Run Code Online (Sandbox Code Playgroud)

要么

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
Run Code Online (Sandbox Code Playgroud)


Sor*_*ner 14

来自其他答案的代码片段可以工作,但是将它们放在代码中的位置并不总是很明显,特别是如果您使用AlertDialog.Builder并遵循官方对话教程,因为它不使用final AlertDialog ...alertDialog.show().

alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Run Code Online (Sandbox Code Playgroud)

比较好

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
Run Code Online (Sandbox Code Playgroud)

因为如果焦点从EditText切换,SOFT_INPUT_STATE_ALWAYS_VISIBLE将隐藏键盘,其中SHOW_FORCED将保持键盘显示直到它被明确解除,即使用户返回主屏幕或显示最近的应用程序.

下面是使用自定义布局创建的AlertDialog的工作代码,其中EditText是用XML定义的.它还将键盘设置为具有"go"键并允许其触发正按钮.

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>
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


sbe*_*zin 11

嗯,这是一个相当古老的帖子,还有一些东西需要补充.
这些是两种简单的方法,可以帮助我控制键盘,它们的工作非常完美:

显示键盘

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

隐藏键盘

public void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
Run Code Online (Sandbox Code Playgroud)


小智 9

让我指出一些额外的信息到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);
      }
   }
});
Run Code Online (Sandbox Code Playgroud)


A.e*_*deh 9

我知道这个问题很老,因为我认为使用扩展功能是显示编辑文本键盘的更好方法

这是我用来显示编辑文本键盘的方法。

kotlin 代码: 只需要调用edittext.showKeyboard()

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

Java代码:

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


jqp*_*liq 7

看看这个讨论它处理手动隐藏和显示输入法.然而,我的感觉是,如果一个专注EditText的没有带来IME,那是因为你正在调用AlertDialog.show()OnCreate()或其他一些在实际呈现屏幕之前引发的方法.移动它OnPostResume()应该在那种情况下解决它我相信.


小智 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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)