텍스트 편집에 초점을 맞출 때 소프트 키보드를 표시하는 방법
.EditText
포커스가 키보드가 ) 저는 두 문제가 (으)ㄹ 수 있습니다.
의 가언제 때.
Activity
나의 표니다나, 의시EditText
초점은 맞추어져 있지만 키보드가 표시되지 않습니다. 키보드를 표시하려면 다시 클릭해야 합니다. (표시되어야 합니다.)Activity
표시됨).되지만 그고키보에서완클료키해보제만되지가드면하릭리드를,▁and만,
EditText
(편집이 끝났기 때문에) 집중하고 싶지 않습니다.
다시 시작하기 위해, 제 문제는 iPhone에 키보드 동기화를 유지하는 것과 더 유사한 것을 갖는 것입니다.EditText
상태(집중됨/집중되지 않음), 물론 물리적인 상태가 있는 경우 소프트 웨어를 제공하지 않습니다.
소프트 키보드를 강제로 표시하려면
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
yourEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
그리고 초점을 제거하기 위해.EditText
가 있습니다.View
초점을 잡기 위해.
닫기 위해 사용할 수 있습니다.
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
대화 상자에서 사용할 수 있습니다.
public void showKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public void closeKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
저도 같은 문제가 있었습니다.편집 직후 텍스트 가시성이 GONE에서 VISIBLE로 변경되어 포커스를 설정하고 소프트 키보드를 표시해야 했습니다.다음 코드를 사용하여 이를 달성했습니다.
new Handler().postDelayed(new Runnable() {
public void run() {
// ((EditText) findViewById(R.id.et_find)).requestFocus();
//
EditText yourEditText= (EditText) findViewById(R.id.et_find);
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));
}
}, 200);
저에게는 100ms 지연으로 작동하지만, 지연 없이 실패하거나 1ms 지연으로 작동하지 않습니다.
코드의 주석이 달린 부분은 일부 장치에서만 작동하는 다른 접근 방식을 보여줍니다.OS 버전 2.2(에뮬레이터), 2.2.1(실제 장치) 및 1.6(에뮬레이터)에서 테스트했습니다.
이 접근법은 저에게 많은 고통을 덜어주었습니다.
키보드를 표시하려면
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
이 방법은 InputMethodManager를 직접 호출하는 것보다 안정적입니다.
닫으려면 다음을 사용합니다.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
다른 방법이 없으면 강제로 표시합니다.
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
그런 다음 나중에 Pause() 등에서 닫으려면 다음을 호출할 수 있습니다.
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
다음 코드는 구글의 SearchView용 4.1 소스 코드에서 도용한 것입니다.작동하는 것 같습니다, 안드로이드의 작은 버전에서도 괜찮습니다.
private Runnable mShowImeRunnable = new Runnable() {
public void run() {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(editText, 0);
}
}
};
private void setImeVisibility(final boolean visible) {
if (visible) {
post(mShowImeRunnable);
} else {
removeCallbacks(mShowImeRunnable);
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
}
그런 다음 Control/Activity가 생성될 때 다음 코드를 추가해야 합니다.(저의 경우 활동이 아닌 복합 컨트롤입니다.)
this.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
setImeVisibility(hasFocus);
}
});
android:windowSoftInputMode="stateAlwaysVisible"
-> 매니페스트 파일에 있습니다.
edittext.requestFocus();
-> 코드로.
이렇게 하면 활동이 나타날 때 편집 텍스트가 요청 포커스를 갖는 소프트 키보드가 열립니다.
저는 최근에 아래 코드로 몇 가지 간단한 경우에 운이 좋았습니다.모든 테스트를 마치지는 않았지만..
EditText input = (EditText) findViewById(R.id.Input);
input.requestFocus();
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));
그리고 키보드가 나타납니다.
소프트 키보드를 강제로 표시해 볼 수 있습니다. 저에게는 효과가 있습니다.
...
dialog.show();
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Kotlin의 경우 다음 확장자를 사용하십시오.
fun EditText.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun EditText.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(this.windowToken, 0)
}
fragment의 경우 작동하는지 확인합니다.
displayName = (EditText) view.findViewById(R.id.displayName);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
가끔 러크드라우그의 대답이 먹히지 않을 때가 있습니다.저는 몇 가지 시행착오를 겪으면서 이런 식으로 해왔습니다.
public static void showKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
public static void hideKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
텍스트 편집 파트:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(getActivity());
} else {
showKeyboard(getActivity());
}
}
});
showSoftInput
나를 위해 전혀 일하지 않았습니다.
입력 모드를 설정해야 한다고 판단했습니다. (여기 매니페스트의 활동 구성 요소)
android:windowSoftInputMode="stateVisible"
키보드를 숨기려면 다음 키보드를 사용합니다.
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
키보드를 표시합니다.
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Kotlin
키보드를 포커스에 표시하기 위한 확장입니다.
이것은 너무 길거나 불완전한 이전 반응의 조합입니다.
이 확장은 메시지 큐에 실행 가능한 파일을 게시하여 포커스를 요청한 후 소프트 키보드를 표시합니다.
fun View.showSoftKeyboard() {
post {
if (this.requestFocus()) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
나중에 필요할 때 원하는 뷰에서 호출:
editText.showSoftKeyboard()
텍스트 편집 보기에서 이 줄을 추가하기만 하면 됩니다.
android:isScrollContainer="true"
그리고 TADA - 키보드가 자동으로 나타나기 시작했습니다!
저는 비슷한 문제를 겪었고 이 간단하고 이상한 해결책을 발견했습니다.
사용자 3392439가 여기서 이미 언급했듯이 초점을 맞춘 키보드의 모양은 XML 파일의 스크롤 구성 요소 존재와 이상하게 연결되어 있습니다.
동일한 XML에 위에서 언급한 줄로 구성된 다른 EditText 뷰가 있으면 현재 EditText 중 어느 것에 초점이 맞추어져 있든 키보드가 나타납니다.
XML 파일에 스크롤 구성요소로 구성된 보기가 하나 이상 있는 경우 키보드가 포커스에 자동으로 나타납니다.
스크롤이 없으면 텍스트 편집을 클릭하여 키보드를 표시해야 합니다.
활동 애니메이션이 소프트 키보드를 비활성화할 수 있다는 것을 알았을 때 소프트 키보드에 대한 문제가 해결되었습니다.당신이 의도를 다음과 같이 부를 때.
i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
그리고.
overridePendingTransition(0, 0);
소프트 키보드를 숨길 수 있지만 표시할 방법이 없습니다.
저는 다양한 상황에서 동일한 문제를 겪었고, 제가 찾은 솔루션은 일부에서는 작동하지만 다른 솔루션에서는 작동하지 않으므로 여기 제가 찾은 대부분의 상황에서 작동하는 결합 솔루션이 있습니다.
public static void showVirtualKeyboard(Context context, final View view) {
if (context != null) {
final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.clearFocus();
if(view.isShown()) {
imm.showSoftInput(view, 0);
view.requestFocus();
} else {
view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
@Override
public void onViewAttachedToWindow(View v) {
view.post(new Runnable() {
@Override
public void run() {
view.requestFocus();
imm.showSoftInput(view, 0);
}
});
view.removeOnAttachStateChangeListener(this);
}
@Override
public void onViewDetachedFromWindow(View v) {
view.removeOnAttachStateChangeListener(this);
}
});
}
}
}
editText.post(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
저는 여기 있는 모든 것을 결합했고 저에게는 효과가 있습니다.
public static void showKeyboardWithFocus(View v, Activity a) {
try {
v.requestFocus();
InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
그것은 나에게 효과가 있었다.키보드를 표시할 수도 있습니다.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
Square에서 얻은 보다 안정적인 솔루션은 다음과 같습니다.
fun View.focusAndShowKeyboard() {
/**
* This is to be called when the window already has focus.
*/
fun View.showTheKeyboardNow() {
if (isFocused) {
post {
// We still post the call, just in case we are being notified of the windows focus
// but InputMethodManager didn't get properly setup yet.
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
requestFocus()
if (hasWindowFocus()) {
// No need to wait for the window to get focus.
showTheKeyboardNow()
} else {
// We need to wait until the window gets focus.
viewTreeObserver.addOnWindowFocusChangeListener(
object : ViewTreeObserver.OnWindowFocusChangeListener {
override fun onWindowFocusChanged(hasFocus: Boolean) {
// This notification will arrive just before the InputMethodManager gets set up.
if (hasFocus) {
this@focusAndShowKeyboard.showTheKeyboardNow()
// It’s very important to remove this listener once we are done.
viewTreeObserver.removeOnWindowFocusChangeListener(this)
}
}
})
}
}
여기서부터 코드 크레딧.
코드 조각입니다.
public void hideKeyboard(Context activityContext){
InputMethodManager imm = (InputMethodManager)
activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//android.R.id.content ( http://stackoverflow.com/a/12887919/2077479 )
View rootView = ((Activity) activityContext)
.findViewById(android.R.id.content).getRootView();
imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
}
public void showKeyboard(Context activityContext, final EditText editText){
final InputMethodManager imm = (InputMethodManager)
activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!editText.hasFocus()) {
editText.requestFocus();
}
editText.post(new Runnable() {
@Override
public void run() {
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
});
}
매니페스트 내부:
android:windowSoftInputMode="stateAlwaysVisible"
처음 시작한 키보드입니다. android:windowSoftInputMode="stateAlwaysHidden"
처음에는 키보드를 숨겼습니다.
저는 또한 사용하는 것을 좋아합니다."adjustPan"
키보드가 시작되면 화면이 자동으로 조정되기 때문입니다.
<activity
android:name="YourActivity"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>
매니페스트 파일에 Android:WindowsSoftInputMode="stateHidden"을 추가하기만 하면 됩니다...
final InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
어떤 답변도 제게 도움이 되지 않았습니다.여기 간단한 방법이 있습니다.
searchEditText.setVisibility(View.VISIBLE);
final Handler handler=new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
searchEditText.requestFocus();
}
}, 400);
requestFocus() 메서드를 400ms 지연했습니다.
위에 제공된 모든 솔루션(EditText에 연결된 OnFocusChangeListener.onFocusChangeListener의 InputMethodManager 상호 작용)은 활동에 단일 편집이 있으면 정상적으로 작동합니다.
제 경우에는 두 가지 편집이 있습니다.
private EditText tvX, tvY;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tvX.setOnFocusChangeListener(this);
tvY.setOnFocusChangeListener(this);
@Override
public void onFocusChange(View v, boolean hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(tvX.hasFocus() || tvY.hasFocus()) {
imm.showSoftInput(v, 0);
} else {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
};
저는 onFocusChange가 hasFocus=true(표시됨)인 tvX에 대해 트리거되지만 hasFocus=true(표시되지 않음)인 tvY에 대해서는 트리거된다는 것을 관찰했습니다.결국 키보드가 보이지 않았습니다.
일반 솔루션은 "EditText 텍스트에 포커스가 있는 경우 키보드 표시"에 올바른 문이 있어야 합니다.
활동의 onResume() 섹션에서 bringKeyboard() 메서드를 호출할 수 있습니다.
onResume() {
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
bringKeyboard(yourEditText);
}
protected boolean bringKeyboard(EditText view) {
if (view == null) {
return false;
}
try {
// Depending if edittext has some pre-filled values you can decide whether to bring up soft keyboard or not
String value = view.getText().toString();
if (value == null) {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
return true;
}
} catch (Exception e) {
Log.e(TAG, "decideFocus. Exception", e);
}
return false;
}
공식 문서에서 읽은 바와 같이 보기를 텍스트 편집과 같은 매개 변수로 전달하는 것이 가장 좋은 답이라고 생각합니다. 하지만 showSoftKeyboard는 풍경에서 작동하지 않는 것 같습니다.
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun closeSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
코틀린의 경우:
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
fun showKeyboard() {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
fun hideKeyboard() {
imm.hideSoftInputFromWindow(phoneNoInputTxt.windowToken, 0);
}
그럼 당신이 원하는 걸 불러요!
언급URL : https://stackoverflow.com/questions/5105354/how-to-show-soft-keyboard-when-edittext-is-focused
'programing' 카테고리의 다른 글
C에서 'atoi' 기능에 대한 경고 표시 (0) | 2023.07.03 |
---|---|
표에서 MIN과 MAX를 모두 선택하는 속도가 예상보다 느립니다. (0) | 2023.06.28 |
log4j2를 사용한 스프링 부트 로깅? (0) | 2023.06.28 |
Woocommerce | 아약스의 클리어 카트 (0) | 2023.06.28 |
ignored 파일을 git 상태 밖으로 유지 (0) | 2023.06.28 |