工具类
程序员文章站
2022-05-19 15:43:00
...
1.控制软键盘
import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
public class EmoticonsKeyboardUtils {
private static final String EXTRA_DEF_KEYBOARDHEIGHT = "DEF_KEYBOARDHEIGHT";
private static final int DEF_KEYBOARD_HEAGH_WITH_DP = 300;
private static int sDefKeyboardHeight = -1;
private static DisplayMetrics getDisplayMetrics(Context context) {
DisplayMetrics dm = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);
return dm;
}
public static int getDisplayWidthPixels(Context context) {
return getDisplayMetrics(context).widthPixels;
}
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int getFontHeight(TextView textView) {
Paint paint = new Paint();
paint.setTextSize(textView.getTextSize());
Paint.FontMetrics fm = paint.getFontMetrics();
return (int) Math.ceil(fm.bottom - fm.top);
}
public static View getRootView(Activity context) {
return ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
}
public static int getDefKeyboardHeight(Context context) {
if (sDefKeyboardHeight < 0) {
sDefKeyboardHeight = dip2px(context, DEF_KEYBOARD_HEAGH_WITH_DP);
}
int height = PreferenceManager.getDefaultSharedPreferences(context).getInt(EXTRA_DEF_KEYBOARDHEIGHT, 0);
return sDefKeyboardHeight = height > 0 && sDefKeyboardHeight != height ? height : sDefKeyboardHeight;
}
public static void setDefKeyboardHeight(Context context, int height) {
if (sDefKeyboardHeight != height) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt(EXTRA_DEF_KEYBOARDHEIGHT, height).commit();
EmoticonsKeyboardUtils.sDefKeyboardHeight = height;
}
}
public static boolean isFullScreen(final Activity activity) {
return (activity.getWindow().getAttributes().flags &
WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0;
}
/**
* 开启软键盘
* @param et
*/
public static void openSoftKeyboard(EditText et) {
if (et != null) {
et.setFocusable(true);
et.setFocusableInTouchMode(true);
et.requestFocus();
InputMethodManager inputManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(et, 0);
}
}
/**
* 关闭软键盘
* @param context
*/
public static void closeSoftKeyboard(Context context) {
if (context == null || !(context instanceof Activity) || ((Activity) context).getCurrentFocus() == null) {
return;
}
try{
View view = ((Activity) context).getCurrentFocus();
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
view.clearFocus();
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
} catch (Exception e){
e.printStackTrace();
}
}
/**
* 关闭软键盘
* 当使用全屏主题的时候,XhsEmoticonsKeyBoard屏蔽了焦点.关闭软键盘时,直接指定 closeSoftKeyboard(EditView)
* @param view
*/
public static void closeSoftKeyboard(View view) {
if (view == null || view.getWindowToken() == null) {
return;
}
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
2.对于图片的压缩 获取视频的图片
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;
/**
* 集合一些图片工具
*
* Created by zhuwentao on 2016-07-22.
*/
public class PhotoBitmapUtils {
/**
* 存放拍摄图片的文件夹
*/
private static final String FILES_NAME = "/MyPhoto";
/**
* 获取的时间格式
*/
public static final String TIME_STYLE = "yyyyMMddHHmmss";
/**
* 图片种类
*/
public static final String IMAGE_TYPE = ".png";
/**
* 缩减文件的大小
*/
public static final long FILE_SIZE=200;
// 防止实例化
private PhotoBitmapUtils() {
}
public static File getimage(String srcPath) {
BitmapFactory.Options newOpts = new BitmapFactory.Options();
// 开始读入图片,此时把options.inJustDecodeBounds 设回true了
newOpts.inJustDecodeBounds = true;
newOpts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);
return compressImage(bitmap);
}
/**
* 缩放大小 缩略图
* */
public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){
// 获得图片的宽高
int width = bm.getWidth();
int height = bm.getHeight();
// 计算缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
return newbm;
}
public static Bitmap createVideoThumbnail(String filePath)
{
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try
{
if (filePath.startsWith("http://")
|| filePath.startsWith("https://")
|| filePath.startsWith("widevine://"))
{
retriever.setDataSource(filePath, new Hashtable<String, String>());
}
else
{
retriever.setDataSource(filePath);
}
bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); //retriever.getFrameAtTime(-1);
}
catch (IllegalArgumentException ex)
{
// Assume this is a corrupt video file
ex.printStackTrace();
}
catch (RuntimeException ex)
{
// Assume this is a corrupt video file.
ex.printStackTrace();
}
finally
{
try
{
retriever.release();
}
catch (RuntimeException ex)
{
// Ignore failures while cleaning up.
ex.printStackTrace();
}
}
return bitmap;
}
/**
* 压缩图片(质量压缩)
* @param bitmap
*/
public static File compressImage(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > FILE_SIZE) { //循环判断如果压缩后图片是否大于500kb,大于继续压缩
baos.reset();//重置baos即清空baos
options -= 10;//每次都减少10
bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
long length = baos.toByteArray().length;
}
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date(System.currentTimeMillis());
String filename = format.format(date);
File file = new File(Environment.getExternalStorageDirectory(),filename+".png");
try {
FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(baos.toByteArray());
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return file;
}
}
3.监听软键盘
window.decorView.addOnLayoutChangeListener {v, left, top, right, down, oldLeft, oldTop, oldRight, oldBottom ->
val rect = Rect()
window.decorView.getWindowVisibleDisplayFrame(rect)
val screenHeight = window.decorView.rootView.height
val heightDifference = screenHeight - rect.bottom
val visible = heightDifference > screenHeight / 3
if (visible) {
} else {
}
}
4.解决CoordinatorLayout 快速拖拽 抖动问题
引入自定义behavior
app:layout_behavior="org.com.qy.myapplication.CustomBehavior"
import android.content.Context;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.OverScroller;
import java.lang.reflect.Field;
public class CustomBehavior extends AppBarLayout.Behavior {
private OverScroller mScroller;
private static final int TYPE_FLING = 1;
private boolean isFlinging;
private boolean shouldBlockNestedScroll;
public CustomBehavior() {
}
public CustomBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
getParentScroller(context);
}
/**
* 反射获得滑动属性。
*
* @param context
*/
private void getParentScroller(Context context) {
if (mScroller != null) return;
mScroller = new OverScroller(context);
try {
Class<?> reflex_class = getClass().getSuperclass().getSuperclass();//父类AppBarLayout.Behavior父类的父类HeaderBehavior
Field fieldScroller = reflex_class.getDeclaredField("mScroller");
fieldScroller.setAccessible(true);
fieldScroller.set(this, mScroller);
} catch (Exception e) {
}
}
//fling上滑appbar然后迅速fling下滑recycler时, HeaderBehavior的mScroller并未停止, 会导致上下来回晃动
@Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
if (mScroller != null) { //当recyclerView 做好滑动准备的时候 直接干掉Appbar的滑动
if (mScroller.computeScrollOffset()) {
mScroller.abortAnimation();
}
}
if (type == ViewCompat.TYPE_NON_TOUCH && getTopAndBottomOffset() == 0) { //recyclerview的惯性比较大 ,会顶在头部一会儿, 到头直接干掉它的滑动
ViewCompat.stopNestedScroll(target, type);
}
if (type == TYPE_FLING) {
isFlinging = true;
}
if (!shouldBlockNestedScroll) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
}
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
}
@Override
public boolean onTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent e) {
switch (e.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
break;
}
return super.onTouchEvent(parent, child, e);
}
@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
shouldBlockNestedScroll = false;
if (isFlinging) {
shouldBlockNestedScroll = true;
}
return super.onInterceptTouchEvent(parent, child, ev);
}
@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int
dxUnconsumed, int dyUnconsumed, int type) {
if (!shouldBlockNestedScroll) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
}
}
@Override
public void onStopNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout abl, View target, int type) {
super.onStopNestedScroll(coordinatorLayout, abl, target, type);
isFlinging = false;
shouldBlockNestedScroll = false;
}
}
上一篇: mysql中表数据与表结构复制语句
下一篇: 通过文件选择器上传文件