public static double getScreenPhysicalSize(Activity ctx) {
DisplayMetrics dm = new DisplayMetrics();
ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);
double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels,2) + Math.pow(dm.heightPixels,2));
return diagonalPixels / (160 * dm.density);
}
2.判断是否是平板(官方用法)
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
3.启动APK的默认Activity
public static void startApkActivity(final Context ctx,String packageName) {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi;
try {
pi = pm.getPackageInfo(packageName,0);
Intent intent = new Intent(Intent.ACTION_MAIN,null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setPackage(pi.packageName);
List apps = pm.queryIntentActivities(intent,0);
ResolveInfo ri = apps.iterator().next();
if (ri != null) {
String className = ri.activityInfo.name;
intent.setComponent(new ComponentName(packageName,className));
ctx.startActivity(intent);
}
} catch (NameNotFoundException e) {
Log.e("startActivity",e);
}
}
4.检测字符串中是否包含汉字
public static boolean checkChinese(String sequence) {
final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";
boolean result = false;
Pattern pattern = Pattern.compile(format);
Matcher matcher = pattern.matcher(sequence);
result = matcher.find();
return result;
}
5.检测字符串中只能包含:中文、数字、下划线(_)、横线(-)
public static boolean checkNickname(String sequence) {
final String format = "[^\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-_]";
Pattern pattern = Pattern.compile(format);
Matcher matcher = pattern.matcher(sequence);
return !matcher.find();
}
6.使用TransitionDrawable实现渐变效果
private void setImageBitmap(ImageView imageView,Bitmap bitmap) {
// Use TransitionDrawable to fade in.
final TransitionDrawable td = new TransitionDrawable(new Drawable[] { new ColorDrawable(android.R.color.transparent),new BitmapDrawable(mContext.getResources(),bitmap) });
//noinspection deprecation
imageView.setBackgroundDrawable(imageView.getDrawable());
imageView.setImageDrawable(td);
td.startTransition(200);
}
7.Dip转px
public static int dipToPX(final Context ctx,float dip) {
return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dip,ctx.getResources().getDisplayMetrics());
}
用途:难免在Activity代码中设置位置、大小等,本方法就很有用了!
总结
以上是编程之家为你收集整理的Android实用代码(1)全部内容,希望文章能够帮你解决Android实用代码(1)所遇到的程序开发问题。
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。