programing

텍스트 편집에 초점을 프로그래밍 방식으로 설정하고 키보드를 표시하는 방법

easyjava 2023. 9. 6. 23:05
반응형

텍스트 편집에 초점을 프로그래밍 방식으로 설정하고 키보드를 표시하는 방법

다음과 같은 보기가 포함된 레이아웃이 있습니다.

<LinearLayout>
<TextView...>
<TextView...>
<ImageView ...>
<EditText...>
<Button...>
</linearLayout>

초점(키보드 표시)을 설정하려면 어떻게 해야 합니까?EditText계획적으로?

이것을 시도해 보았는데, 이것을 실행할 때에만 작동합니다.Activity보통은, 하지만 내가 그것을 시작할 때는TabHost안 돼요동작되지 않습니다.

txtSearch.setFocusableInTouchMode(true);
txtSearch.setFocusable(true);
txtSearch.requestFocus();

시도해 보기:

EditText editText = (EditText) findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

http://developer.android.com/reference/android/view/View.html#requestFocus()

용도:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

이건 내게 효과가 있었어요. 언갈크라이즈 덕분이죠

키보드 표시:

editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);

키보드 숨기기:

InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
final EditText tb = new EditText(this);
tb.requestFocus();
tb.postDelayed(new Runnable() {
    @Override
    public void run() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(tb, InputMethodManager.SHOW_IMPLICIT);
    }
}, 1000);

showSoftInput저한테 전혀 도움이 안 됐어요

모드를 했습니다 : 를 해야 했습니다 했습니다 해야 를 .android:windowSoftInputMode="stateVisible"에 있음 기성 Activity소의)소성기

도움이 되길 바랍니다!

다음은 소프트 키보드를 보여주고 숨기기 위한 코틀린 확장자를 만드는 방법입니다.

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

fun View.hideKeyboard() {
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

그럼 그냥 이렇게 하면 되겠네요.

editText.showKeyboard()
// OR
editText.hideKeyboard()

Android JetpackLifecycle-Aware Components로 Lifecycle을 처리하는 방법 중 하나인 Lifecycle Observer를 사용하는 것이 좋습니다.

Fragment/Activity가 나타나면 키보드를 열고 닫습니다.먼저 EditText(편집 텍스트)에 대해 두 개의 확장 함수를 정의합니다.프로젝트의 모든 위치에 배치할 수 있습니다.

fun EditText.showKeyboard() {
    requestFocus()
    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)
}

Activity가 "Activity/Fragment" " Lifecycle Observer"에 합니다.onResume()아니면onPause:

class EditTextKeyboardLifecycleObserver(private val editText: WeakReference<EditText>) :
    LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun openKeyboard() {
        editText.get()?.postDelayed({ editText.get()?.showKeyboard() }, 100)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun closeKeyboard() {
        editText.get()?.hideKeyboard()
    }
}

그런 다음 프래그먼트/활동에 다음 행을 추가하면 언제든지 Lifecycle Observer를 재사용할 수 있습니다.예: 조각의 경우:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    // inflate the Fragment layout

    lifecycle.addObserver(EditTextKeyboardLifecycleObserver(WeakReference(myEditText)))

    // do other stuff and return the view

}

키보드가 있습니다.키보드 숨기기 및 표시를 위한 도우미 클래스

import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

/**
 * Created by khanhamza on 06-Mar-17.
 */

public class KeyboardHelper {
public static void hideSoftKeyboard(final Context context, final View view) {
    if (context == null) {
        return;
    }
    view.requestFocus();
    view.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}, 1000);
}

public static void hideSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}, 1000);
}


public static void openSoftKeyboard(final Context context, final EditText editText) {
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}, 1000);
}
}

이를 Resume() method에 입력합니다.

binding.etxtSearch.isFocusableInTouchMode = true
binding.etxtSearch.isFocusable = true
binding.etxtSearch.requestFocus() 
val inputMethodManager = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(binding.etxtSearch, InputMethodManager.SHOW_IMPLICIT)

여러 가지 방법을 시도했지만 작동이 안 되는데, 편집 텍스트가 포함된 프래그먼트에서 액티비티로의 공유 전환을 사용하고 있어서 확실하지 않습니다.

그건 그렇고 제 편집 텍스트도 선형 레이아웃으로 감싸져 있습니다.

포커스를 요청하기 위해 약간의 지연을 추가했고 아래의 코드가 저에게 효과가 있었습니다: (Kotlin)

 et_search.postDelayed({
     editText.requestFocus()

     showKeyboard()
 },400) //only 400 is working fine, even 300 / 350, the cursor is not showing

show키보드()

 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
editTxt.setOnFocusChangeListener { v, hasFocus ->
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (hasFocus) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
            } else {
                imm.hideSoftInputFromWindow(v.windowToken, 0)
            }
        }

저는 데이비드 메리만의 최고 답변을 시도해 보았지만 제 경우에도 효과가 없었습니다.하지만 이 코드를 실행하는 제안이 여기서 지연되고 있다는 것을 알게 되었고 그것은 매력적으로 작용합니다.

val editText = view.findViewById<View>(R.id.settings_input_text)

editText.postDelayed({
    editText.requestFocus()

    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT)
}, 100)

답장이 늦었다는 것은 알지만, 2022년에 이것을 하려고 하는 저와 같은 사람들을 위해, 토글소프트 인풋이 더 이상 사용되지 않는다는 것을 알기 위해(레벨 31 기준), showSoft를 사용하는 새로운 접근법이 여기 있습니다.입력:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
editView.requestFocus();
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                        .showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);

토글 소프트인풋을 시도해 보았지만 홈 버튼을 누르면 키보드가 유지되는 등의 몇 가지 문제를 발견했지만 이 접근 방식은 완벽하게 작동했습니다.

키보드를 프로그래밍 방식으로 보여주기 위해 이 코드를 사용하고 있습니다.

binding!!.etAssignToName.postDelayed( {
                mActivity.runOnUiThread {
                    showKeyboard(binding!!.etAssignToName,mContext)
                }
            },300)

fun showKeyboard(editText: EditText, context: Context) {
editText.requestFocus()
val imm: InputMethodManager =
    context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(editText, 0)}

fun View.hideSoftKeyboard(context: Context) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(this.windowToken, 0)}

첫번째 방법:

    etPassword.post(() -> {
        etPassword.requestFocus();
        InputMethodManager manager = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.showSoftInput(etPassword, InputMethodManager.SHOW_IMPLICIT);
    });

두번째 방법:

매니페스트에서:

    <activity
        android:name=".activities.LoginActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateVisible"/>

코드명:

etPassword.requestFocus();

나는 마침내 해결책을 찾았고 그것을 위한 코틀린 수업을 만들었습니다.

object KeyboardUtils {

    fun showKeyboard(editText: EditText) {
        editText.requestFocus()
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(editText, 0)
    }

    fun hideKeyboard(editText: EditText) {
        val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(editText.windowToken, 0)
    }

}

코틀린:

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

fun View.hideKeyboard() {
  val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  imm.hideSoftInputFromWindow(windowToken, 0)
}

용도:

yourEditText.post{
    yourEditText.showKeyboard()
}

다른 사람들처럼 키보드를 보여주기 위해 지연을 추가해야 했지만,after초점 맞추기 YMMV

private fun View.showKeyboard() {
    this.requestFocus()
    this.postDelayed({
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
    }, 100)
}

"OnCreate"에서 커서를 입력 필드로 이동하지만 키보드는 열리지 않습니다.

window().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
)
editText.requestFocus()

그런 다음 사용자가 텍스트를 입력하는 동안:

val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
window.setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
)
imm.showSoftInput(editText, 0)

시간 지연을 설정하지 않고 필요할 때 키보드가 열립니다.텍스트를 입력한 후 다음 작업을 수행해야 합니다.

window.setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN
)
requestFocus()

한 줄의 코드로만 했습니다.

firstInputField.setNextFocusDownId(R.id.id_of_next_targeted_text_field);

저는 이러한 답변들 중 어떤 것도 혼자 힘으로 작업할 수 없었습니다.제가 해결할 수 있는 방법은 다음과 같습니다.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
editText.requestFocus();
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);

저에게 왜 그런 방법이 필요했는지 잘 모르겠습니다. 문서에 따르면 어떤 방법이든 스스로 효과가 있어야 하는 것 같습니다.

언급URL : https://stackoverflow.com/questions/8991522/how-can-i-set-the-focus-and-display-the-keyboard-on-my-edittext-programmatical

반응형