推荐下载android开发实用代码片段集合更新ing.docx
- 文档编号:3401296
- 上传时间:2022-11-22
- 格式:DOCX
- 页数:22
- 大小:23.35KB
推荐下载android开发实用代码片段集合更新ing.docx
《推荐下载android开发实用代码片段集合更新ing.docx》由会员分享,可在线阅读,更多相关《推荐下载android开发实用代码片段集合更新ing.docx(22页珍藏版)》请在冰豆网上搜索。
推荐下载android开发实用代码片段集合更新ing
android开发实用代码片段集合(更新ing)
2016/04/040欢迎转载,但请保留文章原始出处:
)博客园:
cnblogs
农民伯伯:
over140blogs
1、精确获取屏幕尺寸(例如:
3.5、4.0、5.0寸屏幕)
publicstaticdoublegetScreenPhysicalSize(Activityctx){DisplayMetricsdm=newDisplayMet
rics();ctx.getWindowManager().getDefaultDisplay().getMetrics(dm);doublediagonalPixels
=Math.sqrt(Math.pow(dm.widthPixels,2)
Math.pow(dm.heightPixels,2));returndiagonalPixels/(160*dm.density);}一般是7寸以上
是平板
2、判断是否是平板(官方用法)
publicstaticbooleanisTablet(Contextcontext){return(context.getResources().getConfigurati
on().screenLayoutConfiguration.SCREENLAYOUT_SIZE_MASK)
=Configuration.SCREENLAYOUT_SIZE_LARGE;}
3、文字根据状态更改颜色android:
textColor
selectorxmlns:
android=schemas.android/apk/res/androiditemandroid:
color=
#53c1bdandroid:
state_selected=true/itemandroid:
color=#53c1bd
android:
state_focused=true/itemandroid:
color=#53c1bdandroid:
state_pressed=true/
itemandroid:
color=#777777//selector放在res/color/目录下
4、背景色根据状态更改颜色android:
backgroup
selectorxmlns:
android=schemas.android/apk/res/androiditemandroid:
state_selected=
trueshapegradientandroid:
angle=0android:
centerColor=#00a59fandroid:
endColor=
#00a59fandroid:
startColor=#00a59f//shape/itemitemandroid:
state_focused=true
shapegradientandroid:
angle=0android:
centerColor=#00a59fandroid:
endColor=
#00a59fandroid:
startColor=#00a59f//shape/itemitemandroid:
state_pressed=true
shapegradientandroid:
angle=0android:
centerColor=#00a59fandroid:
endColor=
#00a59fandroid:
startColor=#00a59f//shape/itemitemshape
gradientandroid:
angle=0android:
centerColor=#00ff00android:
endColor=00ff00
android:
startColor=00ff00//shape/item/selector
如果直接给背景色color会报错。
5、启动APK的默认Activity
publicstaticvoidstartApkActivity(finalContextctx,StringpackageName){PackageManagerp
m=ctx.getPackageManager();PackageInfopi;try{pi=pm.getPackageInfo(packageName,0);I
ntentintent=newIntent(Intent.ACTION_MAIN,null);intent.addCategory(Intent.CATEGOR
Y_LAUNCHER);intent.setPackage(pi.packageName);ListResolveInfo
apps=pm.queryIntentActivities(intent,0);ResolveInfori=apps.iterator().next();if(ri!
=null){S
tringclassName=ri.activityInfo.name;intent.setComponent(newComponentName(package
Name,className));ctx.startActivity(intent);}}catch(NameNotFoundExceptione){Log.e(
startActivity,e);}}
7、计算字宽
publicstaticfloatGetTextWidth(String
text,floatSize){TextPaintFontPaint=newTextPaint();FontPaint.setTextSize(Size);returnFon
tPaint.measureText(text);}8、获取应用程序下所有Activity
publicstaticArrayListStringgetActivities(Contextctx){ArrayListString
result=newArrayListString
Intentintent=newIntent(Intent.ACTION_MAIN,null);intent.setPackage(ctx.getPackageNa
me());for(ResolveInfoinfo:
ctx.getPackageManager().queryIntentActivities(intent,0)){result
.add(info.activityInfo.name);}returnresult;}
9、检测字符串中是否包含汉字
publicstaticbooleancheckChinese(Stringsequence){finalStringformat=[\\u4E00-
\\u9FA5\\uF900-\\uFA2D]
booleanresult=false;Patternpattern=Patrnpattern=Patternpile(format);Matchermatcher=patt
ern.matcher(sequence);return!
matcher.find();}
11、检查有没有应用程序来接受处理你发出的intent
publicstaticbooleanisIntentAvailable(Contextcontext,Stringaction){final
PackageManagerpackageManager=context.getPackageManager();finalIntentintent=
newIntent(action);ListResolveInfolist=packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);returnlist.size()0;}
12、使用TransitionDrawable实现渐变效果
privatevoidsetImageBitmap(ImageViewimageView,Bitmapbitmap){//UseTransitionDrawa
bletofadein.finalTransitionDrawabletd=newTransitionDrawable(newDrawable[]{newColo
rDrawable(android.R.color.transparent),newBitmapDrawable(mContext.getResources(),bit
map)});//noinspectiondeprecationimageView.setBackgroundDrawable(imageView.getDra
wable());imageView.setImageDrawable(td);td.startTransition(200);}比使用
AlphaAnimation效果要好,可避免出现闪烁问题。
13、扫描指定的文件
sendBroadcast(newIntent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));用
途:
从本软件新增、修改、删除图片、文件某一个文件(音频、视频)需要更新系
统媒体库时使用,不必扫描整个SD卡。
14、Dip转px
publicstaticintdipToPX(finalContextctx,floatdip){return(int)TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,dip,ctx.getResources().getDisplayMetrics());}15、
获取已经安装APK的路径
PackageManagerpm=getPackageManager();for(ApplicationInfoapp:
pm.getInstalledApplic
ations(0)){Log.d(PackageList,package:
app.packageName,sourceDir:
app.sourceDir);}输出如下:
package:
com.tmobile.thememanager,sourceDir:
/system/app/ThemeManager.apkpackage:
c
om.touchtype.swiftkey,sourceDir:
/data/app/com.touchtype.swiftkey-1.apk转载自这里。
16、多进程Preferences数据共享
publicstaticvoidputStringProcess(Contextctx,Stringkey,Stringvalue){SharedPreferencessha
redPreferences=ctx.getSharedPreferences(
preference_mu,Context.MODE_MULTI_PROCESS);Editoreditor=sharedPreferences.edit
();editor.putString(key,value);editormit();}publicstaticStringgetStringProcess(Contextctx,S
tringkey,StringdefValue){SharedPreferencessharedPreferences=ctx.getSharedPreferences(
preference_mu,Context.MODE_MULTI_PROCESS);returnsharedPreferences.getString(k
ey,defValue);}相关文章:
zengrong/post/1687.htm
17、泛型ArrayList转数组
@SuppressWarnings(unchecked)publicstaticTT[]toArray(Class?
cls,ArrayListT
items){if(items==null||items.size()==0){return(T[])Array.newInstance(cls,0);}returnitems.t
oArray((T[])Array.newInstance(cls,items.size()));}
18、保存恢复ListView当前位置
privatevoidsaveCurrentPosition(){if(mListView!
=null){intposition=mListView.getFirstVi
siblePosition();Viewv=mListView.getChildAt(0);inttop=(v==null)?
0:
v.getTop();//保存
position和top}}privatevoidrestorePosition(){if(mFolder!
=null
mListView!
=null){intposition=0;//取出保存的数据inttop=0;//取出保存的数据
mListView.setSelectionFromTop(position,top);}}
可以保存在Preference中或者是数据库中,数据加载完后再设置。
19、调用便携式热点和数据共享设置
publicstaticIntentgetHotspotSetting(){Intentintent=newIntent();intent.setAction(Intent.AC
TION_MAIN);ComponentNamecom=newComponentName(com.android.settings,
com.android.settings.TetherSettingsintent.setComponent(com);returnintent;}
20、式化输出IP地址
publicstaticStringgetIp(Contextctx){returnFormatter.formatIpAddress((WifiManager)ctx.g
etSystemService(Context.WIFI_SERVICE).getConnectionInfo().getIpAddress());}
21、文件夹排序(先文件夹排序,后文件排序)
publicstaticvoidsortFiles(File[]files){Arrays.sort(files,newComparatorFile
(){@Overridepublicintcompare(Filelhs,Filerhs){//返回负数表示o1小于o2,返回0表
示o1和o2相等,返回正数表示o1大于o2。
booleanl1=lhs.isDirectory();booleanl2=rhs.isDirectory();if(l1!
l2)return-1;elseif(!
l1
l2)return1;else{returnlhs.getName()pareTo(rhs.getName());}}});}22、发送不重复的通知
(Notification)
publicstaticvoidsendNotification(Contextcontext,Stringtitle,Stringmessage,Bundleextras){I
ntentmIntent=newIntent(context,FragmentTabsActivity.class);mIntent.setFlags(Intent.FLA
G_ACTIVITY_CLEAR_TOP);mIntent.putExtras(extras);intrequestCode=(int)System.curr
entTimeMillis();PendingIntentmContentIntent=PendingIntent.getActivity(context,request
Code,mIntent,0);NotificationmNotification=newNotificationCompat.Builder(context).setC
ontentTitle(title).setSmallIcon(R.drawable.app_icon).setContentIntent(mContentIntent).set
ContentText(message).build();mNotification.flags|=Notification.FLAG_AUTO_CANCEL
;mNotification.defaults=Notification.DEFAULT_ALL;NotificationManagermNotification
Manager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SE
RVICE);mNotificationManager.notify(requestCode,mNotification);}代码说明:
关键点在这个requestCode,这里使用的是当前系统时间,巧妙的保证了每次都是
一个新的Notification产生。
23、代码设置TextView的样式
使用过自定义Dialog可能马上会想到用如下代码:
newTextView(this,null,R.style.text_style);
但你运行这代码你会发现毫无作用!
正确用法:
newTextView(newContextThemeWrapper(this,R.style.text_style))来自这里。
24、ip地址转成8位十六进制串
/**ip转16进制
*/publicstaticStringipToHex(Stringips){StringBufferresult=newStringBuffer();if(ips!
=null
){StringTokenizerst=newStringTokenizer(ips,.
while(st.hasMoreTokens()){Stringtoken=Integer.toHexString(Integer.parseInt(st.nextToke
n()));if(token.length()==1)token=0
token;result.append(token);}}returnresult.toString();}/**16进制转
ip*/publicstaticStringtexToIp(Stringips){try{StringBufferresult=newStringBuffer();if(ips!
=nullips.length()==8){for(inti=0;i8;i
=2){if(i!
=0)result.append(‘.’);result.append(Integer.parseInt(ips.substring(i,i
2),16));}}returnresult.toString();}catch(NumberFormatExceptionex){Logger.e(ex);}return
}ip:
192.168.68.12816=hex:
c0a84480
25、WebView保留缩放功能但隐藏缩放控件
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
if(DeviceUtils.hasHoneycomb())
mWebView.getSettings().setDisplayZoomControls(false);注意:
setDisplayZoomControls
是在APILevel11中新增。
26、获取网络类型名称
publicstaticStringgetNetworkTypeName(Contextcontext){if(context!
=null){Connectivity
ManagerconnectMgr=(ConnectivityManager)context.getSystemService(Context.CONNE
CTIVITY_SERVICE);if(connectMgr!
=null){NetworkInfoinfo=connectMgr.getActiveNet
workInfo();if(info!
=null){switch(info.getType()){caseConnectivityManager.TYPE_WIFI:
r
eturnWIFI
caseConnectivityManager.TYPE_MOBILE:
returngetNetworkTypeName(info.getSubtype(
));}}}}returngetNetworkTypeName(TelephonyManager.NETWORK_TYPE_UNKNOW
N);}publicstaticStringgetNetworkTypeName(inttype){switch(type){caseTelephonyManag
er.NETWORK_TYPE_GPRS:
returnGPRS
caseTelephonyManager.NETWORK_TYPE_EDGE:
returnEDGE
caseTelephonyManager.NETWORK_TYPE_UMTS:
returnUMTS
caseTelephonyManager.NETWORK_TYPE_HSDPA:
returnHSDPA
caseTelephonyManager.NETWORK_TYPE_HSUPA:
returnHSUPA
caseTelephonyManager.NETWORK_TYPE_HSPA:
returnHSPA
caseTelephonyManager.NETWORK_TYPE_CDMA:
returnCDMA
caseTelephonyManager.NETWORK_TYPE_EVDO_0:
returnCDMA-EvDorev.0
caseTelephonyManager.NETWORK_TYPE_EVDO_A:
returnCDMA-EvDorev.A
caseTelephonyManager.NETWORK_TYPE_EVDO_B:
returnCDMA-EvDorev.B
caseTelephonyManager.NETWORK_TYPE_1xRTT:
returnCDMA-1xRTT
caseTelephonyManager.NETWORK_TYPE_LTE:
returnLTE
cas
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 推荐 下载 android 开发 实用 代码 片段 集合 更新 ing