0

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 able 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.

Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
schlaegerz
  • 377
  • 2
  • 12
  • 1
    As far as I know you should not use setContentView multiple times, see http://stackoverflow.com/questions/6811989 – Daniel Fekete Oct 05 '11 at 05:26
  • Thanks for the help. Is there any good source for these types of android programming tips? I'm new to android programming and I don't know what I should and shouldn't do. – schlaegerz Oct 05 '11 at 18:39

2 Answers2

1

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

}
slkorolev
  • 5,883
  • 1
  • 29
  • 32
0

in Manifest file you can use in your Activity declaration

android:windowSoftInputMode="stateVisible|adjustPan"
MKJParekh
  • 34,073
  • 11
  • 87
  • 98