Android: 텍스트 편집에 초점을 맞출 때 자동으로 소프트 키보드 표시
다음을 사용하여 입력 상자를 표시합니다.AlertDialog.EditText내가 전화를 걸 때 대화 상자 내부는 자동으로 초점이 맞춰집니다.AlertDialog.show()소프트 키보드가 자동으로 표시되지 않습니다.
대화 상자가 표시될 때 소프트 키보드가 자동으로 표시되도록 하려면 어떻게 해야 합니까? (물리적/하드웨어 키보드는 없습니다.)검색 단추를 눌러 전역 검색을 호출할 때와 마찬가지로 소프트 키보드가 자동으로 표시됩니다.
에 수 .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);
}
}
});
키보드를 표시하는 경우:
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);
대화상자를 만든 후 바로 소프트키보드를 요청할 수 있습니다(SDK - r20에서 테스트).
// create dialog
final AlertDialog dialog = ...;
// request keyboard
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
이 예제를 찾았습니다. 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);
저도 같은 문제가 있었고 아래 코드로 해결했습니다.하드웨어 키보드가 있는 전화기에서 어떻게 작동할지 잘 모르겠습니다.
// 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();
<activity
...
android:windowSoftInputMode="stateVisible" >
</activity>
또는
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
다른 답변의 코드 조각은 작동하지만, 특히 사용자가 코드에서 코드를 어디에 배치할지가 항상 명확하지는 않습니다.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;
}
}
나는 이 질문이 오래되었다는 것을 알고 있습니다. 확장 기능을 사용하는 것이 편집 텍스트에 대한 키보드를 보여주는 더 예쁜 방법이라고 생각합니다.
편집 텍스트의 키보드를 표시하는 방법은 다음과 같습니다.
코틀린 코드: 그냥 전화하면 됩니다.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);
}
});
}
꽤 할 것이 . 이, 것은꽤오게지이만물, 것히추있습니다이가할음여전래된시▁well.
키보드를 제어하는 데 도움이 되는 두 가지 간단한 방법은 완벽하게 작동합니다.
키보드 표시
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);
}
유쿠 솔루션에 대한 추가 정보를 알려드리겠습니다. 왜냐하면 저는 이것이 작동하기 어렵다는 것을 알았기 때문입니다!AlertDialog에서 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);
}
}
});
수동으로 IME를 숨기고 표시하는 것을 다루는 이 토론을 보세요. 하지만, 제 생각에는 만약 집중한다면,EditText 것이 . IME를 불러오는 것은 이 IME를 부르고 입니다.AlertDialog.show()의 신의에OnCreate()또는 화면이 실제로 표시되기 전에 환기되는 다른 방법.로 이동OnPostResume()제가 생각하는 경우에는 고쳐야 할 것 같습니다.
, 예, 당은할수로 하시면 .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);
}
}
});
다음과 같은 메시지가 표시되는 경우:
작업 유형에서 정적이 아닌 메서드 getSystemService(String)를 정적으로 참조할 수 없습니다.
컨텍스트를 추가하여 시스템 서비스 호출을 가져옵니다.
그렇게
InputMethodManager imm =
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
내 방법은 Android 11+의 새로운 방법을 사용하며 이전 버전도 지원합니다.
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)
}
}
}
하는 곳이 있거나 되어 있거나 하기 하는 것 .WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM또는WindowManager.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);
대화 상자가 표시될 때 기본적으로 키보드를 열 수 있습니다.
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
원래 질문은 대화상자에 관한 것이고 내 편집 텍스트는 정기적으로 표시됩니다.어쨌든, 저는 이것이 여러분 대부분에게도 효과가 있을 것이라고 생각합니다.이것이 저에게 효과적인 방법입니다(위에서 제안한 최고 등급 방법은 저에게 아무런 도움이 되지 않았습니다).이를 수행하는 사용자 정의 편집 보기가 있습니다(하위 분류는 필요하지 않지만 보기가 표시될 때 포커스를 잡고 싶었기 때문에).
이것은 사실 tidbecks가 대답한 것과 거의 같습니다.저는 사실 그의 대답이 0표여서 전혀 눈치채지 못했습니다.그러면 그냥 댓글 달려고 했는데 너무 길었을 것 같아서 어쨌든 이 글을 끝냈어요.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();
}
}
}
시도 및 사용:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
키보드를 보여주기 위해, 저는 다음을 해야 했습니다.
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
}
에▁where디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);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
활동에 참여할 때 키보드를 자동으로 표시하기 위해 Create()를 호출합니다.
이러한 메소드를 Util 클래스에 넣고 아무 곳에서나 사용합니다.
코틀린
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)
}
자바
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);
}
관심 있는 사람이 있을 경우를 대비해 멋진 코틀린-에스큐 확장 기능을 만들었습니다.
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)
}
많은 시도를 했지만 이것이 저에게 효과가 있었습니다(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()
매니페스트 파일에 필요한 작업에 이 줄을 추가하기만 하면 됩니다.
android:windowSoftInputMode="stateVisible"
이것은 당신에게 좋은 샘플입니다.
<?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>
이 대답을 - 입니다.EditText그래서 당신은 키보드가 사라지도록 무언가를 할 필요가 있습니다.EditText집중력이 떨어집니다.
이 작업은 다음 단계를 수행하여 수행할 수 있습니다.
다음 속성을 추가하여 상위 보기(활동의 내용 보기)를 클릭 가능하고 초점을 맞출 수 있도록 합니다.
android:clickable="true" android:focusableInTouchMode="true"hideKeyboard() 메서드 구현
public void hideKeyboard(View view) { InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY ); }마지막으로 편집 텍스트의 onFocusChangeListener를 설정합니다.
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { hideKeyboard(v); } } });
이거 좀 까다롭네요.저는 이런 식으로 했고 효과가 있었습니다.
1.창에서 소프트 입력을 숨기기 위한 첫 번째 호출.이렇게 하면 소프트 키보드가 보이면 소프트 입력이 숨겨지고 보이지 않으면 아무것도 하지 않습니다.
2. 대화 상자 표시
3. 그런 다음 전화를 걸어 소프트 입력을 전환합니다.
코드:
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);
사용해 보세요.
썸유틸스.자바
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); }
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);
홈 버튼을 누르고 홈 화면으로 이동하면 키보드가 열린 상태로 유지되기 때문입니다.
키보표관이문제련에서 소프트 할 때 발생하는 이 EditText東京의 AlertDialog 도있것입다니을마에 것입니다.AlertDialog.show()EditText 적었습니다를 표시한 후 되었습니다.AlertDialogAPI가 은 API 레벨 21과 제공된다고 합니다. 21과 함께 입니다.AlertDialog.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.
언급URL : https://stackoverflow.com/questions/2403632/android-show-soft-keyboard-automatically-when-focus-is-on-an-edittext
'codememo' 카테고리의 다른 글
| 문자열을 버퍼 노드로 변환 (0) | 2023.08.21 |
|---|---|
| CodeIgniter에서 pconnect 옵션의 장점/단점 (0) | 2023.08.21 |
| 한 번의 활동을 만들기 위한 공유 환경설정 (0) | 2023.08.21 |
| __init_.py에서 참조 'xxx'을(를) 찾을 수 없습니다. (0) | 2023.08.21 |
| Angular2가 비동기 함수 호출을 활성화()할 수 있습니다. (0) | 2023.08.21 |