实现点击输入框外的空白区域隐藏软键盘

实现点击输入框外的空白区域隐藏软键盘

布局文件





java代码
package com.example.admin.keyboarddemo;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

public class BaseActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

/**
 * @Description: 隐藏软键盘
 */
protected void hideInputMethod(){
    final View view = getCurrentFocus();
    if(view != null){
        MainActivity.getMainHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(),0);
            }
        },500);
    }
}

/**
 * @Description:显示软键盘
 */
protected void showInputMethod(){
    View view = getCurrentFocus();
    if (view != null) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }
}

}





package com.example.admin.keyboarddemo;

import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;

public class MainActivity extends BaseActivity implements View.OnClickListener {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn_text);
    btn.setOnClickListener(this);
}
public static Handler getMainHandler(){
    Handler handler = new Handler();
    return handler;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (getCurrentFocus() != null) {
        hideInputMethod();
    }
    return super.onTouchEvent(event);
}

@Override
public void onClick(View v) {
    hideInputMethod();
}
}

注:

所有继承BaseActivity,并且重写onTouchEvent()方法,在方法中调用hideInputMethod()方法
的Avtivity都能实现点击空白区域隐藏软件盘。
showInputMethod()为显示软键盘的方法,使用同上。

你可能感兴趣的:(android)