I'm struggling with virtual keyboard on android. The problem is that I can't bring it up/hide it reliably.
Here's a code which refuses to open the keyboard on three devices I tested(ZTE Blade, Galaxy Nexus and Acer A500).
I can hide the keyboard, and I can toggle it, but I can't show it. I could use toggle to show/hide it, but it's not reliable enough (Since there seems to be no way to see if the keyboard is shown or not).
Full code, see if you can make it work:
package com.test.keyboardtest;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class KeyboardTestActivity extends Activity {
LinearLayout myLayout = null;
TextView myView = null;
Button toggleButton = null;
Button showButton = null;
Button hideButton = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myLayout = new LinearLayout(this);
myView = new TextView(this);
showButton = new Button(this);
hideButton = new Button(this);
toggleButton = new Button(this);
myLayout.setOrientation(LinearLayout.VERTICAL);
myLayout.addView(myView);
myLayout.addView(showButton);
myLayout.addView(hideButton);
myLayout.addView(toggleButton);
showButton.setText("Show Keyboard");
showButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(myView, 0 );
}
});
hideButton.setText("Hide Keyboard");
hideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(myView.getWindowToken(), 0 );
}
});
toggleButton.setText("Toggle Keyboard");
toggleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.toggleSoftInput(0,0);
}
});
this.setContentView(myLayout);
}
}