实用的Android代码片段集合(精)
1、精确获取屏幕尺寸(例如:3.5、4.0、5.0寸屏幕)
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); }
一般是7寸以上是平板
2、判断是否是平板(官方用法)
public static boolean isTablet(Context context) { return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE; }
3、 文字根据状态更改颜色 android:textColor
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="#53c1bd" android:state_selected="true"/> <item android:color="#53c1bd" android:state_focused="true"/> <item android:color="#53c1bd" android:state_pressed="true"/> <item android:color="#777777"/> </selector>
放在res/color/目录下
4、背景色根据状态更改颜色 android:backgroup
1 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 2 <item android:state_selected="true"> 3 <shape> 4 <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" /> 5 </shape> 6 </item> 7 <item android:state_focused="true"> 8 <shape> 9 <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" /> 10 </shape> 11 </item> 12 <item android:state_pressed="true"> 13 <shape> 14 <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" /> 15 </shape> 16 </item> 17 <item> 18 <shape> 19 <gradient android:angle="0" android:centerColor="#00ff00" android:endColor="00ff00" android:startColor="00ff00" /> 20 </shape> 21 </item> 22 </selector>
如果直接给背景色color会报错。
5、启动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<ResolveInfo> 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);
}
}
7、计算字宽
public static float GetTextWidth(String text, float Size) {
TextPaint FontPaint = new TextPaint();
FontPaint.setTextSize(Size);
return FontPaint.measureText(text);
}
注意如果设置了textStyle,还需要进一步设置TextPaint。
8、获取应用程序下所有Activity
public static ArrayList<String> getActivities(Context ctx) {
ArrayList<String> result = new ArrayList<String>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setPackage(ctx.getPackageName());
for (ResolveInfo info : ctx.getPackageManager().queryIntentActivities(intent, 0)) {
result.add(info.activityInfo.name);
}
return result;
}
9、检测字符串中是否包含汉字
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;
}
10、检测字符串中只能包含:中文、数字、下划线(_)、横线(-)
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();
}
11、检查有没有应用程序来接受处理你发出的intent
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
12、使用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); }
比使用AlphaAnimation效果要好,可避免出现闪烁问题。
13、扫描指定的文件
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
用途:从本软件新增、修改、删除图片、文件某一个文件(音频、视频)需要更新系统媒体库时使用,不必扫描整个SD卡
14、Dip转px
public static int dipToPX(final Context ctx, float dip) { return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, ctx.getResources().getDisplayMetrics()); }
用途:难免在Activity代码中设置位置、大小等,本方法就很有用了!
15、获取已经安装APK的路径
PackageManager pm = getPackageManager();
for (ApplicationInfo app : pm.getInstalledApplications(0)) {
Log.d("PackageList", "package: " + app.packageName + ", sourceDir: " + app.sourceDir);
}
输出如下:
package: com.tmobile.thememanager, sourceDir: /system/app/ThemeManager.apk
package: com.touchtype.swiftkey, sourceDir: /data/app/com.touchtype.swiftkey-1.apk
public static void putStringProcess(Context ctx, String key, String value) { SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS); Editor editor = sharedPreferences.edit(); editor.putString(key, value); editor.commit(); } public static String getStringProcess(Context ctx, String key, String defValue) { SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS); return sharedPreferences.getString(key, defValue); }
相关文章:
http://zengrong.net/post/1687.htm
17、泛型ArrayList转数组
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Class<?> cls, ArrayList<T> items) {
if (items == null || items.size() == 0) {
return (T[]) Array.newInstance(cls, 0);
}
return items.toArray((T[]) Array.newInstance(cls, items.size()));
}
18、保存恢复ListView当前位置
private void saveCurrentPosition() {
if (mListView != null) {
int position = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
//保存position和top
}
}
private void restorePosition() {
if (mFolder != null && mListView != null) {
int position = 0;//取出保存的数据
int top = 0;//取出保存的数据
mListView.setSelectionFromTop(position, top);
}
}
可以保存在Preference中或者是数据库中,数据加载完后再设置。
19、调用 便携式热点和数据共享 设置
public static Intent getHotspotSetting() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
ComponentName com = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");
intent.setComponent(com);
return intent;
}
20、格式化输出IP地址
public static String getIp(Context ctx) {
return Formatter.formatIpAddress((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE).
getConnectionInfo().getIpAddress());
}
21、文件夹排序(先文件夹排序,后文件排序)
public static void sortFiles(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File lhs, File rhs) {
//返回负数表示o1 小于o2,返回0 表示o1和o2相等,返回正数表示o1大于o2。
boolean l1 = lhs.isDirectory();
boolean l2 = rhs.isDirectory();
if (l1 && !l2)
return -1;
else if (!l1 && l2)
return 1;
else {
return lhs.getName().compareTo(rhs.getName());
}
}
});
}
22、发送不重复的通知(Notification)
public static void sendNotification(Context context, String title,
String message, Bundle extras) {
Intent mIntent = new Intent(context, FragmentTabsActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mIntent.putExtras(extras);
int requestCode = (int) System.currentTimeMillis();
PendingIntent mContentIntent = PendingIntent.getActivity(context,
requestCode, mIntent, 0);
Notification mNotification = new NotificationCompat.Builder(context)
.setContentTitle(title).setSmallIcon(R.drawable.app_icon)
.setContentIntent(mContentIntent).setContentText(message)
.build();
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotification.defaults = Notification.DEFAULT_ALL;
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(requestCode, mNotification);
}
关键点在这个requestCode,这里使用的是当前系统时间,巧妙的保证了每次都是一个新的Notification产生。
23、代码设置TextView的样式
使用过自定义Dialog可能马上会想到用如下代码:
new TextView(this,null,R.style.text_style);
但你运行这代码你会发现毫无作用!正确用法:
new TextView(new ContextThemeWrapper(this, R.style.text_style))
24、ip地址转成8位十六进制串
1 /** ip转16进制 */ 2 public static String ipToHex(String ips) { 3 StringBuffer result = new StringBuffer(); 4 if (ips != null) { 5 StringTokenizer st = new StringTokenizer(ips, "."); 6 while (st.hasMoreTokens()) { 7 String token = Integer.toHexString(Integer.parseInt(st.nextToken())); 8 if (token.length() == 1) 9 token = "0" + token; 10 result.append(token); 11 } 12 } 13 return result.toString(); 14 } 15 /** 16进制转ip */ 16 public static String texToIp(String ips) { 17 try { 18 StringBuffer result = new StringBuffer(); 19 if (ips != null && ips.length() == 8) { 20 for (int i = 0; i < 8; i += 2) { 21 if (i != 0) 22 result.append('.'); 23 result.append(Integer.parseInt(ips.substring(i, i + 2), 16)); 24 } 25 } 26 return result.toString(); 27 } catch (NumberFormatException ex) { 28 Logger.e(ex); 29 } 30 return ""; 31 }
ip:192.168.68.128 16 =>hex :c0a84480
25、WebView保留缩放功能但隐藏缩放控件
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
if (DeviceUtils.hasHoneycomb())
mWebView.getSettings().setDisplayZoomControls(false);
注意:setDisplayZoomControls是在API Level 11中新增。
26、获取网络类型名称
1 public static String getNetworkTypeName(Context context) { 2 if (context != null) { 3 ConnectivityManager connectMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 4 if (connectMgr != null) { 5 NetworkInfo info = connectMgr.getActiveNetworkInfo(); 6 if (info != null) { 7 switch (info.getType()) { 8 case ConnectivityManager.TYPE_WIFI: 9 return "WIFI"; 10 case ConnectivityManager.TYPE_MOBILE: 11 return getNetworkTypeName(info.getSubtype()); 12 } 13 } 14 } 15 } 16 return getNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOWN); 17 } 18 public static String getNetworkTypeName(int type) { 19 switch (type) { 20 case TelephonyManager.NETWORK_TYPE_GPRS: 21 return "GPRS"; 22 case TelephonyManager.NETWORK_TYPE_EDGE: 23 return "EDGE"; 24 case TelephonyManager.NETWORK_TYPE_UMTS: 25 return "UMTS"; 26 case TelephonyManager.NETWORK_TYPE_HSDPA: 27 return "HSDPA"; 28 case TelephonyManager.NETWORK_TYPE_HSUPA: 29 return "HSUPA"; 30 case TelephonyManager.NETWORK_TYPE_HSPA: 31 return "HSPA"; 32 case TelephonyManager.NETWORK_TYPE_CDMA: 33 return "CDMA"; 34 case TelephonyManager.NETWORK_TYPE_EVDO_0: 35 return "CDMA - EvDo rev. 0"; 36 case TelephonyManager.NETWORK_TYPE_EVDO_A: 37 return "CDMA - EvDo rev. A"; 38 case TelephonyManager.NETWORK_TYPE_EVDO_B: 39 return "CDMA - EvDo rev. B"; 40 case TelephonyManager.NETWORK_TYPE_1xRTT: 41 return "CDMA - 1xRTT"; 42 case TelephonyManager.NETWORK_TYPE_LTE: 43 return "LTE"; 44 case TelephonyManager.NETWORK_TYPE_EHRPD: 45 return "CDMA - eHRPD"; 46 case TelephonyManager.NETWORK_TYPE_IDEN: 47 return "iDEN"; 48 case TelephonyManager.NETWORK_TYPE_HSPAP: 49 return "HSPA+"; 50 default: 51 return "UNKNOWN"; 52 } 53 }
27、Android解压Zip包
1 /** 2 * 解压一个压缩文档 到指定位置 3 * 4 * @param zipFileString 压缩包的名字 5 * @param outPathString 指定的路径 6 * [url=home.php?mod=space&uid=2643633]@throws[/url] Exception 7 */ 8 public static void UnZipFolder(String zipFileString, String outPathString) throws Exception { 9 java.util.zip.ZipInputStream inZip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(zipFileString)); 10 java.util.zip.ZipEntry zipEntry; 11 String szName = ""; 12 while ((zipEntry = inZip.getNextEntry()) != null) { 13 szName = zipEntry.getName(); 14 if (zipEntry.isDirectory()) { 15 // get the folder name of the widget 16 szName = szName.substring(0, szName.length() - 1); 17 java.io.File folder = new java.io.File(outPathString + java.io.File.separator + szName); 18 folder.mkdirs(); 19 } else { 20 java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName); 21 file.createNewFile(); 22 // get the output stream of the file 23 java.io.FileOutputStream out = new java.io.FileOutputStream(file); 24 int len; 25 byte[] buffer = new byte[1024]; 26 // read (len) bytes into buffer 27 while ((len = inZip.read(buffer)) != -1) { 28 // write (len) byte from buffer at the position 0 29 out.write(buffer, 0, len); 30 out.flush(); 31 } 32 out.close(); 33 } 34 }//end of while 35 inZip.close(); 36 }//end of func
28、从assets中读取文本和图片资源
1 /** 从assets 文件夹中读取文本数据 */ 2 public static String getTextFromAssets(final Context context, String fileName) { 3 String result = ""; 4 try { 5 InputStream in = context.getResources().getAssets().open(fileName); 6 // 获取文件的字节数 7 int lenght = in.available(); 8 // 创建byte数组 9 byte[] buffer = new byte[lenght]; 10 // 将文件中的数据读到byte数组中 11 in.read(buffer); 12 result = EncodingUtils.getString(buffer, "UTF-8"); 13 in.close(); 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 return result; 18 } 19 20 /** 从assets 文件夹中读取图片 */ 21 public static Drawable loadImageFromAsserts(final Context ctx, String fileName) { 22 try { 23 InputStream is = ctx.getResources().getAssets().open(fileName); 24 return Drawable.createFromStream(is, null); 25 } catch (IOException e) { 26 if (e != null) { 27 e.printStackTrace(); 28 } 29 } catch (OutOfMemoryError e) { 30 if (e != null) { 31 e.printStackTrace(); 32 } 33 } catch (Exception e) { 34 if (e != null) { 35 e.printStackTrace(); 36 } 37 } 38 return null; 39 }
29、展开、收起状态栏
1 public static final void collapseStatusBar(Context ctx) { 2 Object sbservice = ctx.getSystemService("statusbar"); 3 try { 4 Class<?> statusBarManager = Class.forName("android.app.StatusBarManager"); 5 Method collapse; 6 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { 7 collapse = statusBarManager.getMethod("collapsePanels"); 8 } else { 9 collapse = statusBarManager.getMethod("collapse"); 10 } 11 collapse.invoke(sbservice); 12 } catch (Exception e) { 13 e.printStackTrace(); 14 } 15 } 16 public static final void expandStatusBar(Context ctx) { 17 Object sbservice = ctx.getSystemService("statusbar"); 18 try { 19 Class<?> statusBarManager = Class.forName("android.app.StatusBarManager"); 20 Method expand; 21 if (Build.VERSION.SDK_INT >= 17) { 22 expand = statusBarManager.getMethod("expandNotificationsPanel"); 23 } else { 24 expand = statusBarManager.getMethod("expand"); 25 } 26 expand.invoke(sbservice); 27 } catch (Exception e) { 28 e.printStackTrace(); 29 } 30 }
用途:可用于点击Notifacation之后收起状态栏
30、获取状态栏高度
public static int getStatusBarHeight(Context context){
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, statusBarHeight = 0;
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
statusBarHeight = context.getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return statusBarHeight;
}
31、ListView使用ViewHolder极简写法
public static <T extends View> T getAdapterView(View convertView, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) convertView.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
convertView.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = convertView.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
用法:
@Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feed_item, parent, false); } ImageView thumnailView = getAdapterView(convertView, R.id.video_thumbnail); ImageView avatarView = getAdapterView(convertView, R.id.user_avatar); ImageView appIconView = getAdapterView(convertView, R.id.app_icon);
用起来非常简练,将ViewHolder隐于无形。
32、设置Activity透明
<style name="TransparentActivity" parent="AppBaseTheme"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:colorBackgroundCacheHint">@null</item> <item name="android:windowIsTranslucent">true</item> <item name="android:windowNoTitle">true</item> <item name="android:windowContentOverlay">@null</item> </style>
说明:AppBaseTheme一般是你application指定的android:theme是啥这里就是啥,否则Activity内部的空间风格可能不一致。
用途:用于模拟Dialog效果,比如再Service中没法用Dialog,就可以用Activity来模拟
33、代码切换全屏
//切换到全屏 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN); getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //切换到非全屏 getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
注意:切换到全屏时,底部的虚拟按键仍然是显示的。次方法可多次调用用于切换
用途:播放器界面经常会用到
34、调用开发者选项中显示触摸位置功能
android.provider.Settings.System.putInt(getContentResolver(), "show_touches", 1);
设置1显示,设置0不显示。
35、获取设备上已安装并且可启动的应用列表
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> activities = getPackageManager().queryIntentActivities(intent, 0);
注意:使用getInstalledApplications会返回很多无法启动甚至没有图标的系统应用。
ResolveInfo.activityInfo.applicationInfo也能取到你想要的数据。