Android 键盘事件触发以及监听

一、Android 手动显示和隐藏软键盘

  • 如果输入法在窗口上已经显示,则隐藏,反之则显示
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 
  • view为接受软键盘输入的视图,SHOW_FORCED表示强制显示
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  
imm.showSoftInput(view,InputMethodManager.SHOW_FORCED);  
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘 
  • 调用隐藏系统默认的输入法
// (WidgetSearchActivity是当前的Activity)  
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
  • 获取输入法打开的状态
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);  
boolean isOpen=imm.isActive();//isOpen若返回true,则表示输入法打开 

二、Android 键盘弹起和回落事件监听

AndroidMainfest.xml

 
            
                
                
            
 

MainActivity

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * 捕捉界面键盘弹起动作
 * 例如 京东金融 登陆界面 在输入框获取焦点后键盘弹出把整个布局上移
 * 键盘回落后布局也相应回落
 *
 */
public class MainActivity extends AppCompatActivity {

    private LinearLayout root_view;

    private int screenHeight = 0;
    private int keyHeight = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        initOtherData();
    }

    private void initView() {
        root_view = (LinearLayout) findViewById(R.id.root_view);
    }

    private void initListener() {
        root_view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
                    Toast.makeText(MainActivity.this,"键盘弹起",Toast.LENGTH_SHORT).show();
                } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
                    Toast.makeText(MainActivity.this,"键盘落下",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void initOtherData() {
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        keyHeight = screenHeight / 3;
    }

}

activity_main.xml




  



你也可以看这里
和这里

你可能感兴趣的:(Android 键盘事件触发以及监听)