문제

다음을 사용하여 입력 상자를 표시하고 있습니다. AlertDialog.그만큼 EditText 호출할 때 대화 상자 자체에 자동으로 초점이 맞춰집니다. AlertDialog.show(), 그러나 소프트 키보드는 자동으로 표시되지 않습니다.

대화 상자가 표시될 때 소프트 키보드가 자동으로 표시되도록 하려면 어떻게 해야 합니까?(물리적/하드웨어 키보드는 없습니다).검색 버튼을 눌러 전체 검색을 호출하는 방법과 유사하게 소프트 키보드가 자동으로 표시됩니다.

도움이 되었습니까?

해결책

당신은 초점 리스너를 만들 수 있습니다 EditTextAlertDialog, 그 다음을 얻으십시오 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);

나는 같은 문제가 있었고 다음 코드로 해결했습니다. 하드웨어 키보드가있는 휴대 전화에서 어떻게 작동하는지 잘 모르겠습니다.

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

이 예를 찾았습니다 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);
<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);

초점이 EditText에서 전환되면 Soft_Input_state_always_visible이 키보드를 숨기므로 Show_Forced는 사용자가 홈 화면으로 돌아 오거나 최근 앱을 표시하더라도 키보드가 명시 적으로 해제 될 때까지 키보드를 표시합니다.

아래는 XML에 editText가 정의 된 사용자 정의 레이아웃을 사용하여 생성 된 ALERTDIALOG의 작동 코드입니다. 또한 키보드를 "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>

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

글쎄, 이것은 꽤 오래된 게시물입니다. 아직 추가할 내용이 있습니다.
다음은 키보드를 제어하는 ​​데 도움이 되는 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);
}

유쿠 솔루션에 대한 추가 정보를 알려 드리겠습니다. 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);
      }
   }
});

보세요 이것 수동으로 숨기고 IME를 보여주는 토론. 그러나 내 느낌은 집중한다면 EditText 당신이 전화하기 때문입니다. 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)를 정적으로 참조 할 수 없습니다.

추가 해보세요 문맥 getsystemservice 호출.

그래서

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

원래 질문은 대화 상자와 관련이 있으며 내 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();
        }
    }

}

문제는 텍스트를 입력하는 장소가 처음에 (또는 중첩 또는 무언가) 숨겨져 있기 때문에 AlertDialog가 자동으로 플래그를 설정하는 것 같습니다. 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);

시도 및 사용 :

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
}

어디에 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);

이 방법을 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);
}

누구나 관심이있는 경우 멋진 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)
}

이것은 당신에게 좋은 샘플입니다 :

<?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. 그래서 당신은 KeyBaord를 때리기 위해 무언가를해야합니다. 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. 마지막으로, edittext의 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).getWind‌​owToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);

이 시도

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

많은 것을 시도했지만 이것이 저에게 효과가있는 것입니다 (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()

보고 있습니다 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의 키보드를 표시하는 데 사용하는 방법은 다음과 같습니다.

Kotlin 코드 :전화하면됩니다 edittext.showKeyboard()

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

자바 코드 :

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);
      }
    });
  }
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

활동에 올 때 키보드를 자동으로 표시하기 위해 oncreate ()로 호출합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top