66

Android 开发中的代码片段(1)

 5 years ago
source link: http://fullscreendeveloper.cn/articles/2018/09/09/1536492082162.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言

收集Android开发中常用的一些代码片段,留存记录

代码

禁止截屏

对安全性要求比较高的APP可以用得到

getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE)

禁止输入特殊字符

经历过 Tester 的无限摧残得出的结果,主要是使用正则表达式来完成校验。

/**
 * 禁止输入表情以及特殊字符
 */
public static class EmojiExcludeFilter implements InputFilter {
	@Override
	public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
		for (int i = start; i < end; i++) {
			int type = Character.getType(source.charAt(i));
			if (type == Character.SURROGATE || type == Character.OTHER_SYMBOL) {
				return "";
			}
		}
		String speChat = "[`~!@#$%^&*()+=|{}':;'\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘”“’?]";
		Pattern pattern = Pattern.compile(speChat);
		Matcher matcher = pattern.matcher(source.toString());
		if (matcher.find()) {
			return "";
		} else {
			return null;
		}
	}
}

调用如下:

edtRemark.setFilters(new InputFilter[]{new UIHelper.EmojiExcludeFilter()});

## ViewPager无限滑动

用来做轮播图(Banner)会用得到。

mViewPager.setOnPageChangeListener(new OnPageChangeListener() {
   @Override
   public void onPageSelected(int arg0) {

   }
   @Override
   public void onPageScrolled(int arg0, float arg1, int arg2) {
       if(arg0 == 0 && (arg1 <= 0.001f && arg1 >= -0.001f)){
           mVp.setCurrentItem(list.size()-2, false);
       }else if(arg0 == list.size() - 1){
           mVp.setCurrentItem(1, false);
       }
   }
   @Override
   public void onPageScrollStateChanged(int arg0) {

   }
});

判断ViewPager的滑动方向

vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            float lastPositionOffset = 0L;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (lastPositionOffset > positionOffset && positionOffset != 0) {
                    //右滑
                    Log.e("direction", "right");
                } else if (lastPositionOffset < positionOffset && positionOffset != 0) {
                    //左滑
                    Log.e("direction", "left");
                }
                lastPositionOffset = positionOffset;
            }

            @Override
            public void onPageSelected(int position) { }

            @Override
            public void onPageScrollStateChanged(int state) {}
        });

根据百分比计算颜色值

/**
 * 根据当前的百分比 计算两个颜色之间的值
 *
 * @param fraction 分值
 * @param startValue 开始颜色
 * @param endValue 结束颜色
 * @return 计算得出的颜色
 */
public static Integer evaluate(float fraction, Integer startValue, Integer endValue) {

	float[] startHsv = new float[3];
	float[] endHsv = new float[3];
	float[] outHsv = new float[3];

	// 把 ARGB 转换成 HSV
	Color.colorToHSV(startValue, startHsv);
	Color.colorToHSV(endValue, endHsv);

	// 根据当前的百分比(fraction)所对应的颜色值
	if (endHsv[0] - startHsv[0] > 180) {
		endHsv[0] -= 360;
	} else if (endHsv[0] - startHsv[0] < -180) {
		endHsv[0] += 360;
	}
	outHsv[0] = startHsv[0] + (endHsv[0] - startHsv[0]) * fraction;
	if (outHsv[0] > 360) {
		outHsv[0] -= 360;
	} else if (outHsv[0] < 0) {
		outHsv[0] += 360;
	}
	outHsv[1] = startHsv[1] + (endHsv[1] - startHsv[1]) * fraction;
	outHsv[2] = startHsv[2] + (endHsv[2] - startHsv[2]) * fraction;

	// 根据当前的百分比(fraction)所对应的透明度
	int alpha = startValue >> 24 + (int) ((endValue >> 24 - startValue >> 24) * fraction);

	// 把 HSV 转换回 ARGB 返回
	return Color.HSVToColor(alpha, outHsv);
}

ViewPager之间联动

//-----------------------------联动 下面的内容
	int width = vpContent.getWidth();
	//滑动内部Viewpager
	vpContent.scrollTo((int) (width * position + width * positionOffset), 0);
	//-----------------------------联动 下面的内容

AlertDialog状态不变黑

主要解决使用AlertDialog状态栏变黑的问题

public class CustomDialog extends AlertDialog {
    public CustomDialog(@NonNull Context context) {
        super(context);
    }

    public CustomDialog(@NonNull Context context, @StyleRes int theme) {
        super(context, theme);
    }

    protected CustomDialog(@NonNull Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		// 请使用自己的工具类获取屏幕的高度
        int screenHeight = ScreenUtils.getScreenHeight(getContext());
		// 请使用自己的工具类获取到状态栏的高度
        int statusBarHeight = ScreenUtils.getStatusHeight(getContext());
        int dialogHeight = screenHeight - statusBarHeight;
        getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, dialogHeight);
    }
}

判断屏幕旋转方向

// 判断Android当前的屏幕是横屏还是竖屏。横竖屏判断
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			//竖屏
		} else {
			//横屏
		}

手动设置方向

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

# 最后

未完待续、敬请期待!

我的博客地址

RnA7Vra.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK