开发者

Android: The soft keyboard won't appear for a text view after a setContentView

开发者 https://www.devze.com 2023-04-10 13:25 出处:网络
I am having a problem with a textview in my application. When the application first runs it works perfectly fine, but when I swap to a different view using setContentView and then back again the soft

I am having a problem with a textview in my application. When the application first runs it works perfectly fine, but when I swap to a different view using setContentView and then back again the soft keyboard will no long open but I am a开发者_运维百科ble to select the text.

Here is the code snippet of when I try to switch back:

 public void setToMain(String _word)
    {
        setContentView(R.layout.main);
        mWordInput = (TextView) findViewById(R.id.wordInput);
        mWordInput.setText(_word);
    }

Even if I don't call setText I get the problem.


I had a similar problem with the soft keyboard; though in my case it would not show even without switching views with setContentView. After some experimenting I've found the solution which still works for me. The idea was to intercept soft keyboard showing/hiding for any EditText descendant. For this I overrode onWindowFocusChanged of the Activity.

The trick was in hiding the keyboard when it is not needed anymore.

As you can see I used toggleSoftInput with SHOW_IMPLICIT instead of any HIDE constant. In this case IMEManager would retain the keyboard visible only if the focused view requires it otherwise it will be hidden.

private boolean softInputActive;

@Override
public void onWindowFocusChanged(boolean hasFocus) {

    super.onWindowFocusChanged(hasFocus);

    InputMethodManager IMEManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    View focusedView = getCurrentFocus();

    // Find the primitive focused view (not ViewGroup)
    while (focusedView instanceof ViewGroup) {
        focusedView = ((ViewGroup) focusedView).getFocusedChild();
    }


    if (hasFocus) {

        if (focusedView instanceof EditText && focusedView.isEnabled()
                && !IMEManager.isActive(focusedView)) {
            IMEManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            softInputActive = true;
        }
    } else if (softInputActive) {
        if (focusedView != null && IMEManager.isActive()) {
            IMEManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
        }
        softInputActive = false;
    }

}


in Manifest file you can use in your Activity declaration

android:windowSoftInputMode="stateVisible|adjustPan"
0

精彩评论

暂无评论...
验证码 换一张
取 消