android开发实用代码片段

来源:互联网 发布:mysql入门经典 编辑:程序博客网 时间:2024/06/05 21:10

这里积累了一些不常见确又很实用的代码,详情内容来自农民伯伯。博客园:http://www.cnblogs.com  农民伯伯: http://over140.cnblogs.com


1、 精确获取屏幕尺寸(例如:3.5、4.0、5.0寸屏幕) 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static double getScreenPhysicalSize(Activity ctx) {  
  2.         DisplayMetrics dm = new DisplayMetrics();  
  3.         ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);  
  4.         double diagonalPixels = Math.sqrt(Math.pow(dm.widthPixels, 2) + Math.pow(dm.heightPixels, 2));  
  5.         return diagonalPixels / (160 * dm.density);  
  6.     }  
一般是7寸以上是平板

 

2、 判断是否是平板(官方用法)

   
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static boolean isTablet(Context context) {  
  2.         return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;  
  3.     }  

 

3、 文字根据状态更改颜色 android:textColor 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  2.     <item android:color="#53c1bd" android:state_selected="true"/>  
  3.     <item android:color="#53c1bd" android:state_focused="true"/>  
  4.     <item android:color="#53c1bd" android:state_pressed="true"/>  
  5.     <item android:color="#777777"/>  
  6. </selector>  

   放在res/color/目录下

 

4、背景色根据状态更改颜色 android:backgroup

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  2.   
  3.     <item android:state_selected="true"><shape>  
  4.   
  5.             <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" />  
  6.         </shape></item>  
  7.     <item android:state_focused="true"><shape>  
  8.             <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" />  
  9.         </shape></item>  
  10.     <item android:state_pressed="true"><shape>  
  11.             <gradient android:angle="0" android:centerColor="#00a59f" android:endColor="#00a59f" android:startColor="#00a59f" />  
  12.         </shape></item>  
  13.     <item><shape>  
  14.             <gradient android:angle="0" android:centerColor="#00ff00" android:endColor="00ff00" android:startColor="00ff00" />  
  15.         </shape></item>  
  16.   
  17. </selector>  

如果直接给背景色color会报错。

 

5、 启动APK的默认Activity


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void startApkActivity(final Context ctx, String packageName) {  
  2.     PackageManager pm = ctx.getPackageManager();  
  3.     PackageInfo pi;  
  4.     try {  
  5.         pi = pm.getPackageInfo(packageName, 0);  
  6.         Intent intent = new Intent(Intent.ACTION_MAIN, null);  
  7.         intent.addCategory(Intent.CATEGORY_LAUNCHER);  
  8.         intent.setPackage(pi.packageName);  
  9.   
  10.         List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);  
  11.   
  12.         ResolveInfo ri = apps.iterator().next();  
  13.         if (ri != null) {  
  14.             String className = ri.activityInfo.name;  
  15.             intent.setComponent(new ComponentName(packageName, className));  
  16.             ctx.startActivity(intent);  
  17.         }  
  18.     } catch (NameNotFoundException e) {  
  19.         Log.e("startActivity", e);  
  20.     }  
  21. }  

 

7、计算字宽

   
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static float GetTextWidth(String text, float Size) {  
  2.         TextPaint FontPaint = new TextPaint();  
  3.         FontPaint.setTextSize(Size);  
  4.         return FontPaint.measureText(text);  
  5.     }  

注意如果设置了textStyle,还需要进一步设置TextPaint。 


8、获取应用程序下所有Activity

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;line-height: 1.5;"></span><pre name="code" class="java">public static ArrayList<String> getActivities(Context ctx) {  
  2.       ArrayList<String> result = new ArrayList<String>();  
  3.       Intent intent = new Intent(Intent.ACTION_MAIN, null);  
  4.       intent.setPackage(ctx.getPackageName());  
  5.       for (ResolveInfo info : ctx.getPackageManager().queryIntentActivities(intent, 0)) {  
  6.           result.add(info.activityInfo.name);  
  7.       }  
  8.       return result;  
  9.   }  

9、检测字符串中是否包含汉字

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static boolean checkChinese(String sequence) {  
  2.         final String format = "[\\u4E00-\\u9FA5\\uF900-\\uFA2D]";  
  3.         boolean result = false;  
  4.         Pattern pattern = Pattern.compile(format);  
  5.         Matcher matcher = pattern.matcher(sequence);  
  6.         result = matcher.find();  
  7.         return result;  
  8.     }  
 

10、检测字符串中只能包含:中文、数字、下划线(_)、横线(-)

  
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static boolean checkNickname(String sequence) {  
  2.        final String format = "[^\\u4E00-\\u9FA5\\uF900-\\uFA2D\\w-_]";  
  3.        Pattern pattern = Pattern.compile(format);  
  4.        Matcher matcher = pattern.matcher(sequence);  
  5.        return !matcher.find();  
  6.    }   

 

11、检查有没有应用程序来接受处理你发出的intent

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static boolean isIntentAvailable(Context context, String action) {  
  2.     final PackageManager packageManager = context.getPackageManager();  
  3.     final Intent intent = new Intent(action);  
  4.     List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);  
  5.     return list.size() > 0;  
  6. }  

12、使用TransitionDrawable实现渐变效果 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. private void setImageBitmap(ImageView imageView, Bitmap bitmap) {  
  2.         // Use TransitionDrawable to fade in.  
  3.         final TransitionDrawable td = new TransitionDrawable(new Drawable[] { new ColorDrawable(android.R.color.transparent), new BitmapDrawable(mContext.getResources(), bitmap) });  
  4.         //noinspection deprecation  
  5.             imageView.setBackgroundDrawable(imageView.getDrawable());  
  6.         imageView.setImageDrawable(td);  
  7.         td.startTransition(200);  
  8.     }  

 比使用AlphaAnimation效果要好,可避免出现闪烁问题。

 

13、 扫描指定的文件 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));  

  用途:从本软件新增、修改、删除图片、文件某一个文件(音频、视频)需要更新系统媒体库时使用,不必扫描整个SD卡。

 

14、dip转px

 
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static int dipToPX(final Context ctx, float dip) {  
  2.       return (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, ctx.getResources().getDisplayMetrics());  
  3.   }  

用途:难免在Activity代码中设置位置、大小等,本方法就很有用了!

15、获取已经安装APK的路径

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. PackageManager pm = getPackageManager();  
  2.   
  3. for (ApplicationInfo app : pm.getInstalledApplications(0)) {  
  4.      Log.d("PackageList""package: " + app.packageName + ", sourceDir: " + app.sourceDir);  
  5. }  
  6.   
  7.     输出如下:  
  8. package: com.tmobile.thememanager, sourceDir: /system/app/ThemeManager.apk  
  9. package: com.touchtype.swiftkey, sourceDir: /data/app/com.touchtype.swiftkey-1.apk  

16、 多进程Preferences数据共享

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void putStringProcess(Context ctx, String key, String value) {  
  2.         SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);  
  3.         Editor editor = sharedPreferences.edit();  
  4.         editor.putString(key, value);  
  5.         editor.commit();  
  6.     }  
  7.   
  8.     public static String getStringProcess(Context ctx, String key, String defValue) {  
  9.         SharedPreferences sharedPreferences = ctx.getSharedPreferences("preference_mu", Context.MODE_MULTI_PROCESS);  
  10.         return sharedPreferences.getString(key, defValue);  
  11.     }  

相关文章:http://zengrong.net/post/1687.htm

17、泛型ArrayList转数组

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. @SuppressWarnings("unchecked")  
  2.     public static <T> T[] toArray(Class<?> cls, ArrayList<T> items) {  
  3.         if (items == null || items.size() == 0) {  
  4.             return (T[]) Array.newInstance(cls, 0);  
  5.         }  
  6.         return items.toArray((T[]) Array.newInstance(cls, items.size()));  
  7.     }  


 

18、 保存恢复ListView当前位置

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. private void saveCurrentPosition() {  
  2.         if (mListView != null) {  
  3.             int position = mListView.getFirstVisiblePosition();  
  4.             View v = mListView.getChildAt(0);  
  5.             int top = (v == null) ? 0 : v.getTop();  
  6.             //保存position和top  
  7.         }  
  8.     }  
  9.       
  10.     private void restorePosition() {  
  11.         if (mFolder != null && mListView != null) {  
  12.             int position = 0;//取出保存的数据  
  13.             int top = 0;//取出保存的数据  
  14.             mListView.setSelectionFromTop(position, top);  
  15.         }  
  16.     }  

可以保存在Preference中或者是数据库中,数据加载完后再设置。 

 

19、调用 便携式热点和数据共享 设置

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static Intent getHotspotSetting() {  
  2.         Intent intent = new Intent();  
  3.         intent.setAction(Intent.ACTION_MAIN);  
  4.         ComponentName com = new ComponentName("com.android.settings""com.android.settings.TetherSettings");  
  5.         intent.setComponent(com);  
  6.         return intent;  
  7.     }  

 

20、 格式化输出IP地址

  
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static String getIp(Context ctx) {  
  2.        return Formatter.formatIpAddress((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE).getConnectionInfo().getIpAddress());  
  3.    }  


21、 文件夹排序(先文件夹排序,后文件排序)

 

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void sortFiles(File[] files) {  
  2.         Arrays.sort(files, new Comparator<File>() {  
  3.   
  4.             @Override  
  5.             public int compare(File lhs, File rhs) {  
  6.                 //返回负数表示o1 小于o2,返回0 表示o1和o2相等,返回正数表示o1大于o2。   
  7.                 boolean l1 = lhs.isDirectory();  
  8.                 boolean l2 = rhs.isDirectory();  
  9.                 if (l1 && !l2)  
  10.                     return -1;  
  11.                 else if (!l1 && l2)  
  12.                     return 1;  
  13.                 else {  
  14.                     return lhs.getName().compareTo(rhs.getName());  
  15.                 }  
  16.             }  
  17.         });  
  18.     }  

22、发送不重复的通知(Notification)

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public static void sendNotification(Context context, String title,  
  2.             String message, Bundle extras) {  
  3.         Intent mIntent = new Intent(context, FragmentTabsActivity.class);  
  4.         mIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
  5.         mIntent.putExtras(extras);  
  6.   
  7.         int requestCode = (int) System.currentTimeMillis();  
  8.   
  9.         PendingIntent mContentIntent = PendingIntent.getActivity(context,  
  10.                 requestCode, mIntent, 0);  
  11.   
  12.         Notification mNotification = new NotificationCompat.Builder(context)  
  13.                 .setContentTitle(title).setSmallIcon(R.drawable.app_icon)  
  14.                 .setContentIntent(mContentIntent).setContentText(message)  
  15.                 .build();  
  16.         mNotification.flags |= Notification.FLAG_AUTO_CANCEL;  
  17.         mNotification.defaults = Notification.DEFAULT_ALL;  
  18.   
  19.         NotificationManager mNotificationManager = (NotificationManager) context  
  20.                 .getSystemService(Context.NOTIFICATION_SERVICE);  
  21.   
  22.         mNotificationManager.notify(requestCode, mNotification);  
  23.     }  

代码说明:关键点在这个requestCode,这里使用的是当前系统时间,巧妙的保证了每次都是一个新的Notification产生。 

 

23、代码设置TextView的样式

使用过自定义Dialog可能马上会想到用如下代码:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. new TextView(this,null,R.style.text_style);  
但你运行这代码你会发现毫无作用!正确用法:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. new TextView(new ContextThemeWrapper(this, R.style.text_style))  

 

24、 ip地址转成8位十六进制串

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  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. /** 16进制转ip */  
  17. public static String texToIp(String ips) {  
  18.     try {  
  19.         StringBuffer result = new StringBuffer();  
  20.         if (ips != null && ips.length() == 8) {  
  21.             for (int i = 0; i < 8; i += 2) {  
  22.                 if (i != 0)  
  23.                     result.append('.');  
  24.                 result.append(Integer.parseInt(ips.substring(i, i + 2), 16));  
  25.             }  
  26.         }  
  27.         return result.toString();  
  28.     } catch (NumberFormatException ex) {  
  29.         Logger.e(ex);  
  30.     }  
  31.     return "";  
  32. }  

ip:192.168.68.128 16 =>hex :c0a84480

 

25、WebView保留缩放功能但隐藏缩放控件

       
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. mWebView.getSettings().setSupportZoom(true);  
  2.         mWebView.getSettings().setBuiltInZoomControls(true);  
  3.         if (DeviceUtils.hasHoneycomb())  
  4.               mWebView.getSettings().setDisplayZoomControls(false);  

注意:setDisplayZoomControls是在API Level 11中新增。

 

26、获取网络类型名称

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  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.   
  19.    public static String getNetworkTypeName(int type) {  
  20.        switch (type) {  
  21.        case TelephonyManager.NETWORK_TYPE_GPRS:  
  22.            return "GPRS";  
  23.        case TelephonyManager.NETWORK_TYPE_EDGE:  
  24.            return "EDGE";  
  25.        case TelephonyManager.NETWORK_TYPE_UMTS:  
  26.            return "UMTS";  
  27.        case TelephonyManager.NETWORK_TYPE_HSDPA:  
  28.            return "HSDPA";  
  29.        case TelephonyManager.NETWORK_TYPE_HSUPA:  
  30.            return "HSUPA";  
  31.        case TelephonyManager.NETWORK_TYPE_HSPA:  
  32.            return "HSPA";  
  33.        case TelephonyManager.NETWORK_TYPE_CDMA:  
  34.            return "CDMA";  
  35.        case TelephonyManager.NETWORK_TYPE_EVDO_0:  
  36.            return "CDMA - EvDo rev. 0";  
  37.        case TelephonyManager.NETWORK_TYPE_EVDO_A:  
  38.            return "CDMA - EvDo rev. A";  
  39.        case TelephonyManager.NETWORK_TYPE_EVDO_B:  
  40.            return "CDMA - EvDo rev. B";  
  41.        case TelephonyManager.NETWORK_TYPE_1xRTT:  
  42.            return "CDMA - 1xRTT";  
  43.        case TelephonyManager.NETWORK_TYPE_LTE:  
  44.            return "LTE";  
  45.        case TelephonyManager.NETWORK_TYPE_EHRPD:  
  46.            return "CDMA - eHRPD";  
  47.        case TelephonyManager.NETWORK_TYPE_IDEN:  
  48.            return "iDEN";  
  49.        case TelephonyManager.NETWORK_TYPE_HSPAP:  
  50.            return "HSPA+";  
  51.        default:  
  52.            return "UNKNOWN";  
  53.        }  
  54.    }  

 

27、Android解压Zip包

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. /** 
  2.      * 解压一个压缩文档 到指定位置 
  3.      *  
  4.      * @param zipFileString 压缩包的名字 
  5.      * @param outPathString 指定的路径 
  6.      * @throws 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.   
  13.         while ((zipEntry = inZip.getNextEntry()) != null) {  
  14.             szName = zipEntry.getName();  
  15.   
  16.             if (zipEntry.isDirectory()) {  
  17.   
  18.                 // get the folder name of the widget  
  19.                 szName = szName.substring(0, szName.length() - 1);  
  20.                 java.io.File folder = new java.io.File(outPathString + java.io.File.separator + szName);  
  21.                 folder.mkdirs();  
  22.   
  23.             } else {  
  24.   
  25.                 java.io.File file = new java.io.File(outPathString + java.io.File.separator + szName);  
  26.                 file.createNewFile();  
  27.                 // get the output stream of the file  
  28.                 java.io.FileOutputStream out = new java.io.FileOutputStream(file);  
  29.                 int len;  
  30.                 byte[] buffer = new byte[1024];  
  31.                 // read (len) bytes into buffer  
  32.                 while ((len = inZip.read(buffer)) != -1) {  
  33.                     // write (len) byte from buffer at the position 0  
  34.                     out.write(buffer, 0, len);  
  35.                     out.flush();  
  36.                 }  
  37.                 out.close();  
  38.             }  
  39.         }//end of while  
  40.   
  41.         inZip.close();  
  42.   
  43.     }  

28、 从assets中读取文本和图片资源

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  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.     }  

0 0
原创粉丝点击