网上有很多点击空白处隐藏软键盘的方法,但是试了很多,在一些复杂的界面中就不行了,根本的问题还是在于Android中的事件分发机制了,但是很多人又不是很懂,所以今天直接来一套代码,希望对你有用。
//使editText点击外部时候失去焦点
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {//点击editText控件外部
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
assert v != null;
UIUtils.hideSoftInput(v);
if (editText != null) {
editText.clearFocus();
}
}
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
return getWindow().superDispatchTouchEvent(ev) || onTouchEvent(ev);
}
EditText editText = null;
public boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
editText = (EditText) v;
int[] leftTop = {0, 0};
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
return !(event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom);
}
return false;
}
中间有一个Utils工具类,在这里也给大家吧,希望对你有用。
Utils.Class:
package com.project.evaluationmobile.util;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.LayoutRes;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.project.evaluationmobile.base.BaseApplication;
import java.io.File;
/**
* Created by liuyuli on 2017/5/27 0027.
*/
public class UIUtils {
private static Toast toast;
/**
* 全局 Context
*
* @return Context
*/
public static Context getContext() {
return BaseApplication.getApplication();
}
/**
* 获取主线程的handler
*/
public static Handler getHandler() {
return BaseApplication.getMainThreadHandler();
}
// 判断当前的线程是不是在主线程
public static boolean isRunInMainThread() {
return android.os.Process.myTid() == BaseApplication.getMainThreadId();
}
/**
* 获取资源
*/
public static Resources getResources() {
return getContext().getResources();
}
/**
* 获取文字
*/
public static String getString(int resId) {
return getResources().getString(resId);
}
/**
* 获取文字数组
*/
public static String[] getStringArray(int resId) {
return getResources().getStringArray(resId);
}
/**
* 获取dimen
*/
public static int getDimens(int resId) {
return getResources().getDimensionPixelSize(resId);
}
/**
* 获取drawable
*/
public static Drawable getDrawable(int resId) {
return ContextCompat.getDrawable(UIUtils.getContext(), resId);
}
/**
* 获取drawableId
*/
public static int getDrawableId(String resName) {
int indentify = getResources().getIdentifier(getContext().getPackageName() + ":drawable/" +
resName, null, null);
return indentify;
}
/**
* 获取颜色
*/
public static int getColor(int resId) {
return ContextCompat.getColor(UIUtils.getContext(), resId);
}
/**
* 获取颜色选择器
*/
public static ColorStateList getColorStateList(int resId) {
return ContextCompat.getColorStateList(UIUtils.getContext(), resId);
}
/**
* dip转换px
*/
public static int dip2px(int dip) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (dip * scale + 0.5f);
}
/**
* px转换dip
*/
public static int px2dip(int px) {
final float scale = getResources().getDisplayMetrics().density;
return (int) (px / scale + 0.5f);
}
/**
* 获取屏幕的宽 单位px
*
* @return int
*/
public static int getScreenWidth() {
return getResources().getDisplayMetrics().widthPixels;
}
/**
* 获取屏幕的高 单位px
*
* @return int
*/
public static int getScreenHeight() {
return getResources().getDisplayMetrics().heightPixels;
}
/**
* get Screen Density
*
* @return
*/
public static int getScreenDensity() {
return getResources().getDisplayMetrics().densityDpi;
}
/**
* 吐司
*
* @param text 内容
*/
public static void showToast(final CharSequence text) {
if (TextUtils.isEmpty(text)) {
return;
}
if (UIUtils.isRunInMainThread()) {
UIUtils.showT(text);
} else {
UIUtils.getHandler().post(new Runnable() {
@Override
public void run() {
UIUtils.showT(text);
}
});
}
}
private static void showT(CharSequence text){
if (toast == null) {
toast = Toast.makeText(getContext(), text, Toast.LENGTH_LONG);
} else {
toast.setText(text);
}
toast.show();
}
/**
* 吐司
*
* @param resId 资源文件 string
*/
public static void showToast(int resId) {
if (toast == null) {
toast = Toast.makeText(getContext(), resId, Toast.LENGTH_LONG);
} else {
toast.setText(resId);
}
toast.show();
}
public static void showNull(){
UIUtils.showToast("服务器开小差啦, 请谅解");
}
/**
* 有父布局时使用
*
* @param resoure
* @param root
* @param attchToRoot
* @return 填充的view
*/
public static View inflate(@LayoutRes int resoure, ViewGroup root, boolean attchToRoot) {
return LayoutInflater.from(getContext()).inflate(resoure, root, attchToRoot);
}
/**
* 没有父布局时使用
*
* @param resoure
* @return 填充的 view
*/
public static View inflate(@LayoutRes int resoure) {
return LayoutInflater.from(getContext()).inflate(resoure, null);
}
/**
* 打开apk
*
* @param mActivity 当前页面
* @param filePath 文件路径
*/
public static void install(FragmentActivity mActivity, String filePath) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
File file = new File(filePath);
//兼容7.0
if (Build.VERSION.SDK_INT >= 24) {
uri = FileProvider.getUriForFile(mActivity.getApplicationContext(), UIUtils.getContext().getPackageName()
+ ".fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//兼容8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean hasInstallPermission = mActivity.getPackageManager().canRequestPackageInstalls();
if (!hasInstallPermission) {
UIUtils.showToast("不允许安装未知来源的应用,请设置为允许");
UIUtils.startInstallPermissionSettingActivity(mActivity);
return;
}
}
} else {
uri = Uri.fromFile(file);
}
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri , "application/vnd.android.package-archive");
mActivity.startActivity(intent);
}
/**
* 跳转到设置-允许安装未知来源-页面
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private static void startInstallPermissionSettingActivity(Context context) {
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 隐藏软件盘
*
* @param v
* @return 是否隐藏
*/
public static Boolean hideSoftInput(View v) {
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
return imm.hideSoftInputFromWindow(v.getWindowToken(), 2);
}
return false;
}
/**
* 弹出软件盘
*
* @param v
* @return 是否弹出
*/
public static Boolean showSoftInput(View v) {
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
return imm.showSoftInput(v, 0);
}
return false;
}
/**
* 格式化html代码
*
* @param str html代码
* @return str
*/
public static String fromHtml(String str) {
// 从API level 24开始,fromHtml(String)被废弃,使用fromHtml(String source, int flags) 代替
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY).toString().trim();
} else {
return Html.fromHtml(str).toString().trim();
}
}
/**
* 格式化html代码 加载图片
*
* @param str html代码
* @return str
*/
public static void fromHtml(String str, TextView textView) {
if (str == null) {
str = "";
}
// 从API level 24开始,fromHtml(String)被废弃,使用fromHtml(String source, int flags) 代替
MImageGetter imageGetter = new MImageGetter(textView, UIUtils.getContext());
Spanned spanned;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
spanned = Html.fromHtml(str, Html.FROM_HTML_MODE_LEGACY, imageGetter, null);
} else {
spanned = Html.fromHtml(str, imageGetter, null);
}
textView.setText(spanned);
}
public static class MImageGetter implements Html.ImageGetter {
Context c;
TextView container;
public MImageGetter(TextView text, Context c) {
this.c = c;
this.container = text;
}
@Override
public Drawable getDrawable(String source) {
final LevelListDrawable drawable = new LevelListDrawable();
Glide.with(c).load(source).asBitmap().into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
if (resource != null) {
BitmapDrawable bitmapDrawable = new BitmapDrawable(UIUtils.getResources(), resource);
drawable.addLevel(1, 1, bitmapDrawable);
int width = resource.getWidth();
int height = resource.getHeight();
if (width > UIUtils.getScreenWidth()) {
width = UIUtils.getScreenWidth();
height = resource.getHeight() * UIUtils.getScreenWidth() / resource.getWidth();
}
drawable.setBounds(0, 0, width, height);
drawable.setLevel(1);
container.invalidate();
container.setText(container.getText());
}
}
});
return drawable;
}
}
//
// String html = "下面是第一张图片了 " + "<img src='https://timgsa.baidu
// .com/timg?image&quality=80&size=b9999_10000&sec=1508153665976&di=08fc4ce7bd10132f4017dcd60a76706c&imgtype=0
// &src=http%3A%2F%2Fm.qqzhi.com%2Fupload%2Fimg_5_3999773639D904124002_23.jpg'/>" +
// "这也是第二张图片" + "<img src='https://ss1.baidu
// .com/9vo3dSag_xI4khGko9WTAnF6hhy/image/h%3D200/sign=9d3833093f292df588c3ab158c305ce2
// /d788d43f8794a4c274c8110d0bf41bd5ad6e3928.jpg'/>" +
// "最后一张" + "<img src = 'http://f.hiphotos.baidu
// .com/image/h%3D200/sign=3d746172a4efce1bf52bcfca9f50f3e8/bba1cd11728b47101489df48c0cec3fdfd03238b.jpg'/>";
// // tv_index.setText(UIUtils.fromHtml(data.getName()));
// String html2 = "<p>\n" +
// " <span style=\"color: rgb(255, 0, 0);\"><strong><span style=\"text-decoration: underline;" +
// "\"><em>是统计软件投入金额而<img src='https://timgsa.baidu
// .com/timg?image&quality=80&size=b9999_10000&sec=1508153665976&di=08fc4ce7bd10132f4017dcd60a76706c&imgtype=0
// &src=http%3A%2F%2Fm.qqzhi.com%2Fupload%2Fimg_5_3999773639D904124002_23.jpg'" +
// "/>通过玩儿挂多少个地方官的风格的双方各</em></span></strong></span>\n" +
// "</p>\n";
// tv4.setText(Html.fromHtml(html2, new UIUtils.MImageGetter(tv4, mActivity), null));
}
好了,到这里应该可以了,记录一下。
谢谢~~