An example analysis of Android's soft keyboard

  • 2020-06-19 11:42:49
  • OfStack

This paper illustrates the usage of soft keyboard in Android development. Share to everybody for everybody reference. The details are as follows:

There are two ways to open a soft keyboard. One is showSoftInput, one is toggleSoftInput.


package com.example.dd; 
import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.inputmethod.InputMethodManager; 
import android.widget.Button; 
import android.widget.EditText; 
public class MainActivity extends Activity { 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    final EditText ed2 = (EditText) findViewById(R.id.editText2);
    Button b1 = (Button) findViewById(R.id.button1); 
    b1.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
        ed2.requestFocus(); 
        show(ed2); 
      } 
    });
    Button b2 = (Button) findViewById(R.id.button2);
    b2.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        toggle();
      }
    });
  }
  private void show(EditText ed2) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(ed2, InputMethodManager.SHOW_IMPLICIT);
  }
  private void toggle() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(0, 0);
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
}

The show method must have its first parameter, requestFocus, before it can be used. You can see the comments for the show method:

Synonym for showSoftInput(View, int, ResultReceiver) without a result receiver: explicitly request that the current input method's soft input area be shown to the user, if needed.

The last two words, if needed, mean that the soft keyboard pops up only if the method is called and it is really necessary to display the keyboard.

The toggle method turns the soft keyboard on and off at will.

Hopefully, this article has helped you with your Android programming.


Related articles: