Android开发中的小技巧

转自:http://blog.csdn.net/guxiao1201/article/details/40655661


简介:

startActivities (Intent[] intents)
setError (CharSequence error)
动画reverse ()
addLinks (TextView text, int mask)
SystemClock public static void sleep (long ms)
registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)
在Gradle脚本中使用该标签可以修改在Manifest中定义的VersionName
Activity public void recreate ()
checkSignatures (String pkg1, String pkg2)
android:duplicateParentState/android:addStatedFromChildren
android:clipChildren
android:fillViewport
android:tileMode
SparseArray
PackageManger.setComponentEnabledSetting使用这个方法可以开启和禁用四大组件
View public static int generateViewId ()

public voidstartActivities(Intent[]intents)

Added in API level 11

  • 该方法和我们平常用到的startActivity非常相似,只不过将Intent[]中的Intent所指向的跳转目标Activity从后往前依次添加到返回栈中。跳转完后如果按Back键的话会发现返回的顺序和Intent[]中的顺序前后一致。

Same asstartActivities(Intent[], Bundle)with no options specified.

Parameters
intents The intents to start.
Throws
android.content.ActivityNotFoundException
public static booleanisEmpty(CharSequencestr)
Added in API level 1

  • 我经常在项目中使用,判断字符创是否为空或是否为null非常方便。

Returns true if the string is null or 0-length.

Parameters
str the string to be examined
Returns
  • true if str is null or zero length
public staticSpannedfromHtml(Stringsource)
Added in API level 1

  • 一个很方便格式化Html代码的方法,但因为处理速度不太快,所以我不太经常用它。不建议用该方法处理String样式,通常建议使用Spannable来处理。

Returns displayable styled text from the provided HTML string. Any <img> tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.

This uses TagSoup to handle real HTML, including all of the brokenness found in the wild.

public voidsetError(CharSequenceerror)
Added in API level 1

  • 在TextView上不太常用,更多用在EditText上(EditText继承自TextView)提示用户输入非法。还有个多态方法setError(CharSequence error,Drawable icon)来让开发者自定义错误提示图片。
效果图:

Sets the right-hand compound drawable of the TextView to the "error" icon and sets an error message that will be displayed in a popup when the TextView has focus. The icon and error message will be reset to null when any key events cause changes to the TextView's text. If theerrorisnull, the error message and icon will be cleared.

 
    
public staticStringgetStackTraceString(Throwabletr)
Added in API level 1

  • 有时候我们希望程序抛出异常时能把异常信息保存到制定目录的文件中,getStackTraceString就可以将异常信息转换成字符串的形式。
使用示例:
[java] view plain copy
  1. try{
  2. //TODO
  3. }catch(Exceptione){
  4. StringexceptionStr=Log.getStackTraceString(e);
  5. }

Handy function to get a loggable stack trace from a Throwable

Parameters
tr An exception to log
public staticLayoutInflaterfrom(Contextcontext)
Added in API level 1

  • 和冗长的getSystemService()说Goodbye。

Obtains the LayoutInflater from the given context.

public abstractFilegetCacheDir()
Added in API level 1

  • 获取应用默认缓存路径“/data/data/应用包名/cache”

Returns the absolute path to the application specific cache directory on the filesystem. These files will be ones that get deleted first when the device runs low on storage. There is no guarantee when these files will be deleted.Note: you should notrelyon the system deleting these files for you; you should always have a reasonable maximum, such as 1 MB, for the amount of space you consume with cache files, and prune those files when exceeding that space.

Returns
  • The path of the directory holding application cache files.
public voidreverse()
Added in API level 11

  • 因为当调用这个方法时,如果动画正在播放,可以反向播放动画直到回播放的原点。所以我喜欢用它来平滑的结束动画的播放。

Plays the ValueAnimator in reverse. If the animation is already running, it will stop itself and play backwards from the point reached when reverse was called. If the animation is not currently running, then it will start from the end and play backwards. This behavior is only set for the current animation; future playing of the animation will use the default behavior of playing forward.


Formatter public staticStringformatFileSize(Contextcontext, long number)

Added in API level 3

  • 将文件的大小由字节转换成KB、MB甚至G。再也不用手动去和1024较真了。

Formats a content size to be in the form of bytes, kilobytes, megabytes, etc

Parameters
context Context to use to load the localized units
number size value to be formatted
Returns
  • formatted string with the number
Linkifypublic static final booleanaddLinks(TextViewtext, int mask)
Added in API level 1

Scans the text of the provided TextView and turns all occurrences of the link types indicated in the mask into clickable links. If matches are found the movement method for the TextView is set to LinkMovementMethod.

StaticLayout

这个类并不常用,一般只有在自定义View时遇到长串文字需要换行时用到

Activitypublic voidonBackPressed()
Added in API level 5

  • 这个就很常见了,用于在Activity中拦截返回键事件。(Fragment中可没有这个方法,要想在Fragment中拦截返回键事件请参考我的另一篇博客优雅的让Fragment监听返回键

Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

GestureDetector
用来做一些常见用户交互的监听,比如点击,滑动等。一般用于自定义控件。
Detects various gestures and events using the suppliedMotionEvents. TheGestureDetector.OnGestureListenercallback will notify users when a particular motion event has occurred. This class should only be used withMotionEvents reported via touch (don't use for trackball events). To use this class:

ActivityManagerpublic intgetMemoryClass()
Added in API level 5

  • 通过这个方法可以知道系统还能给APP分配多少内存使用。

Return the approximate per-application memory class of the current device. This gives you an idea of how hard a memory limit you should impose on your application to let the overall system work best. The returned value is in megabytes; the baseline Android memory class is 16 (which happens to be the Java heap limit of those devices); some device with more memory may return 24 or even higher numbers.

SystemClockpublic static voidsleep(long ms)
Added in API level 1

  • 还在为测试网络延迟烦恼么?用这个方法可以很方便的模拟网络延迟,而且不会抛出InterruptedException

Waits a given number of milliseconds (of uptimeMillis) before returning. Similar tosleep(long), but does not throwInterruptedException;interrupt()events are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.

Parameters
ms to sleep before returning, in milliseconds of uptime.
ViewStub
  • 开发中经常遇到动态显示布局的需求,一般都通过View.GONE/View.VISIBLE来控制,但这样会比较耗费资源。一个推荐的方法是在布局xml中使用ViewStub标签。ViewStub只有在手动被Inflate时才会被初始化。详见Android实战技巧:ViewStub的应用
DisplayMetrics.densitypublic floatdensity
Added in API level 1

  • 经常使用DisplayMetrics来获取屏幕高度和宽度,此外,还可以通过它获取屏幕密度

[java] view plain copy
  1. DisplayMetricsdm=newDisplayMetrics();
  2. getWindowManager().getDefaultDisplay().getMetrics(dm);


The logical density of the display. This is a scaling factor for the Density Independent Pixel unit, where one DIP is one pixel on an approximately 160 dpi screen (for example a 240x320, 1.5"x2" screen), providing the baseline of the system's display. Thus on a 160dpi screen this density value will be 1; on a 120 dpi screen it would be .75; etc.

This value does not exactly follow the real screen size (as given byxdpiandydpi, but rather is used to scale the size of the overall UI in steps based on gross changes in the display dpi. For example, a 240x320 screen will have a density of 1 even if its width is 1.8", 1.3", etc. However, if the screen resolution is increased to 320x480 but the screen size remained 1.5"x2" then the density would be increased (probably to 1.5).



UrlQuerySanitizer

  • 一个很方便用来处理url链接的工具类,之前开发过程中遇到需要处理支付宝网页url,获取里面post参数,当时使用String的各种接口进行处理,如果用UrlQuerySanitizer的话就简单多了。比如现在有个Url=http://example.com/?name=Mark,我们使用UrlQuerySanitizer拿到name的值:
[java] view plain copy
  1. UrlQuerySanitizersanitizer=newUrlQuerySanitizer("http://example.com/?name=Mark");
  2. sanitizer.setAllowUnregisteredParamaters(true);
  3. Stringname=sanitizer.getValue("name");

Fragmentpublic voidsetArguments(Bundleargs)
Added in API level 11

  • 在初始化Fragment时向Fragment传参的一个很方便的接口,在Fragment中使用getArguments()来接收。

Supply the construction arguments for this fragment. This can only be called before the fragment has been attached to its activity; that is, you should call it immediately after constructing the fragment. The arguments supplied here will be retained across fragment destroy and creation.

LocalBroadcastManager
  • 导入support-v4就可使用LocalBroadcasrManager,和普通的广播相比,LocalBroadcast的范围只是本应内,所以更有效率,更省资源

PhoneNumberUtilspublic staticStringformatNumber(StringphoneNumber,StringdefaultCountryIso)
Added in API level 1

  • PhoneNumverUtils提供了一系列方法用来格式化电话号码
[java] view plain copy
  1. Stringnum="031185203009";
  2. PhoneNumberUtilsutil=newPhoneNumberUtils();
  3. StringnumFormated=util.formatNumber(num,"CN");
numFormated = 0311-8520-3009

Breaks the given number down and formats it according to the rules for the country the number is from.

Parameters
source The phone number to format
Returns
  • A locally acceptable formatting of the input, or the raw input if formatting rules aren't known for the number
Applicationpublic voidregisterActivityLifecycleCallbacks(Application.ActivityLifecycleCallbackscallback)
Added in API level 14
  • 4.0以后新增的一个很方便的回调,callback中有一系列Activity生命周期的方法,例如OnActivityCreated、onActivityDestory和onActivityPaused等。可以在这些方法中一些统筹的逻辑功能,比如统计Activity的使用频率。
versionNameSuffix
  • 在Gradle脚本中使用该标签可以修改在Manifest中定义的VersionName
Genymotion
  • 一个比较好用的安卓模拟器,分为免费版、个人版和商业版,其中免费版提供了从2.3到4.4版本的SDK,并带有GPS和摄像头功能。我经常使用这个模拟器做博客Demo的gif图。免费版百度网盘链接:http://pan.baidu.com/s/1kTj2Nu3
Activitypublic voidrecreate()
Added in API level 11

  • 强制一个Activity重新创建自己一个新实例的方法,调用该方法目标Activity会重新走一遍自己的生命周期。

Cause this Activity to be recreated with a new instance. This results in essentially the same flow as when the Activity is created due to a configuration change -- the current instance will go through its lifecycle toonDestroy()and a new instance then created after it.

PackageManagerpublic abstract intcheckSignatures(Stringpkg1,Stringpkg2)
Added in API level 1

  • 检查两个apk安装包的签名是否一样,一样的话返回值>0否则返回值<0

Compare the signatures of two packages to determine if the same signature appears in both of them. If they do contain the same signature, then they are allowed special privileges when working with each other: they can share the same user-id, run instrumentation against each other, etc.

Parameters
pkg1 First package name whose signature will be compared.
pkg2 Second package name whose signature will be compared.
Returns

Activitypublic booleanisChangingConfigurations()
Added in API level 11

Check to see whether this activity is in the process of being destroyed in order to be recreated with a new configuration. This is often used inonStop()to determine whether the state needs to be cleaned up or will be passed on to the next instance of the activity viaonRetainNonConfigurationInstance().

Returns
  • If the activity is being torn down in order to be recreated with a new configuration, returns true; else returns false.
ViewTreeObserver

  • 可以注册监听正在屏幕上显示的视图树中任何视图状态的变化,我经常用来视图初始化完成后获取某个控件的尺寸。

A view tree observer is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change.... A ViewTreeObserver should never be instantiated by applications as it is provided by the views hierarchy. Refer togetViewTreeObserver()for more information.

DatabaseUtils
  • 一个包装了一系列数据库操作方法的工具类(不过我没用过,还是喜欢手动敲sql)

android:weightSum

  • 如果想实现一个Button,宽度占据屏幕宽度的50%怎么办?代码动态计算?尝试结合使用android:weightSum和android:layout_weight吧。参考博客:合用weightSum属性和layout_weight属性

Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

Must be a floating point value, such as "1.2".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbolweightSum.

android:duplicateParentState/android:addStatedFromChildren

  • 使用这个属性来应对那些挑剔的UI再好不过了。之前还苦恼父控件和点击状态怎么和子控件同步,直到看到这个属性真实相见恨晚。但使用过程中需注意这两个属性只是传递点击状态而不会执行点击事件。参考博客:Android View与View之间的状态关联处理

When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbolduplicateParentState.

android:clipChildren

  • 设置这个属性后子控件就可以在父控件的范围之外进行绘制了,编写动画时再也不用一层多余的FrameLayout。

Defines whether a child is limited to draw inside of its bounds or not. This is useful with animations that scale the size of the children to more than 100% for instance. In such a case, this property should be set to false to allow the children to draw outside of their bounds. The default value of this property is true.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbolclipChildren.

Related Methods
android:fillViewport

  • 当开发者需要设置一个内容不足以填充整个屏幕的ScrollView全屏时,设置fill_parent是不起作用的,那么使用这个属性吧。

Defines whether the scrollview should stretch its content to fill the viewport.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbolfillViewport.

android:tileMode

  • 用来设置Bitmap显示方式,有平铺、重复等。例如设置重复显示
[html] view plain copy
  1. <xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. android:id="@+id/MainLayout"
  4. xmlns:android="http://schemas.android.com/apk/res/android"
  5. android:layout_width="fill_parent"
  6. android:layout_height="fill_parent"
  7. android:orientation="vertical"
  8. android:background="@drawable/backrepeat"
  9. >
backrepeat.xml
[html] view plain copy
  1. <bitmap
  2. xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:src="@drawable/repeatimg"
  4. android:tileMode="repeat"
  5. android:dither="true"/>



Defines the tile mode. When the tile mode is enabled, the bitmap is repeated. Gravity is ignored when the tile mode is enabled. Default value is "disabled".

Must be one of the following constant values.

Constant Value Description
disabled -1 Do not tile the bitmap. This is the default value.
clamp 0 Replicates the edge color.
repeat 1 Repeats the bitmap in both direction.
mirror 2 Repeats the shader's image horizontally and vertically, alternating mirror images so that adjacent images always seam.

This corresponds to the global attribute resource symboltileMode.

android:enterFadeDuration/android:exitFadeDuration
Added in API level 11

  • 为selector设置渐变效果,示例:
[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <selectorxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:enterFadeDuration="500"
  4. android:exitFadeDuration="500">
  5. <itemandroid:state_focused="true"
  6. android:drawable="@color/press"/>
  7. <item
  8. android:state_pressed="true"
  9. android:drawable="@color/press"/>
  10. <item
  11. android:drawable="@color/normal"/>
  12. </selector>


Amount of time (in milliseconds) to fade out an old state drawable.

Must be an integer value, such as "100".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

Constant Value:16843533 (0x0101030d)
android:scaleType

Controls how the image should be resized or moved to match the size of this ImageView.

Must be one of the following constant values.

Constant Value Description
matrix 0
fitXY 1
fitStart 2
fitCenter 3
fitEnd 4
center 5
centerCrop 6
centerInside 7

This corresponds to the global attribute resource symbolscaleType.

<merge>

PopupWindow
  • 在一些经常用到的控件中都能看到PopupWindow的身影,比如actionbar、autocompleteTextView等。PopupWindow可用于创建悬浮窗口
ThumbnailUtils
  • 可以很方便的创建视频的缩略图,甚至还可以指定缩略图的尺寸
Public Constructors
<nobr style="margin-bottom:0px"></nobr> <nobr style="margin-bottom:0px"><span class="sympad" style="margin-right:2px; margin-bottom:0px"><a target="_blank" href="https://developer.android.com/reference/android/media/ThumbnailUtils.html#ThumbnailUtils()" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">ThumbnailUtils</a></span>()</nobr>
Public Methods
<nobr style="margin-bottom:0px">static<a target="_blank" href="https://developer.android.com/reference/android/graphics/Bitmap.html" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">Bitmap</a></nobr> <nobr><span class="sympad" style="margin-right:2px"><a target="_blank" href="https://developer.android.com/reference/android/media/ThumbnailUtils.html#createVideoThumbnail(java.lang.String,%20int)" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">createVideoThumbnail</a></span>(<a target="_blank" href="https://developer.android.com/reference/java/lang/String.html" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">String</a>filePath, int kind)</nobr>
Create a video thumbnail for a video.
<nobr style="margin-bottom:0px">static<a target="_blank" href="https://developer.android.com/reference/android/graphics/Bitmap.html" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">Bitmap</a></nobr> <nobr><span class="sympad" style="margin-right:2px"><a target="_blank" href="https://developer.android.com/reference/android/media/ThumbnailUtils.html#extractThumbnail(android.graphics.Bitmap,%20int,%20int,%20int)" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">extractThumbnail</a></span>(<a target="_blank" href="https://developer.android.com/reference/android/graphics/Bitmap.html" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">Bitmap</a>source, int width, int height, int options)</nobr>
Creates a centered bitmap of the desired size.
<nobr style="margin-bottom:0px">static<a target="_blank" href="https://developer.android.com/reference/android/graphics/Bitmap.html" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">Bitmap</a></nobr> <nobr><span class="sympad" style="margin-right:2px"><a target="_blank" href="https://developer.android.com/reference/android/media/ThumbnailUtils.html#extractThumbnail(android.graphics.Bitmap,%20int,%20int)" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">extractThumbnail</a></span>(<a target="_blank" href="https://developer.android.com/reference/android/graphics/Bitmap.html" style="color:rgb(37,138,175); text-decoration:none; margin-bottom:0px">Bitmap</a>source, int width, int height)</nobr>
Creates a centered bitmap of the desired size.
SparseArray
  • SparseArray是Android为<Integer,Object>类型的HashMap专门写的类,目的是为了提供效率,其核心算法是折半查找。

SparseArrays map integers to Objects. Unlike a normal array of Objects, there can be gaps in the indices. It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping.

Note that this container keeps its mappings in an array data structure, using a binary search to find keys. The implementation is not intended to be appropriate for data structures that may contain large numbers of items. It is generally slower than a traditional HashMap, since lookups require a binary search and adds and removes require inserting and deleting entries in the array. For containers holding up to hundreds of items, the performance difference is not significant, less than 50%.

To help with performance, the container includes an optimization when removing keys: instead of compacting its array immediately, it leaves the removed entry marked as deleted. The entry can then be re-used for the same key, or compacted later in a single garbage collection step of all removed entries. This garbage collection will need to be performed at any time the array needs to be grown or the the map size or entry values are retrieved.

It is possible to iterate over the items in this container usingkeyAt(int)andvalueAt(int). Iterating over the keys usingkeyAt(int)with ascending values of the index will return the keys in ascending order, or the values corresponding to the keys in ascending order in the case ofvalueAt(int).

PackageMangerpublic abstract voidsetComponentEnabledSetting(ComponentNamecomponentName, int newState, int flags)
Added in API level 1

  • 使用这个方法可以开启和禁用四大组件。开始我很纳闷为什么要禁用组件?后来通过查看android 禁用和开启四大组件的方法博文,发现这个方法可以作为后期性能优化方法之一。

Set the enabled setting for a package component (activity, receiver, service, provider). This setting will override any enabled state which may have been set by the component in its manifest.

Parameters
componentName The component to enable
newState The new enabled state for the component. The legal values for this state are:COMPONENT_ENABLED_STATE_ENABLED,COMPONENT_ENABLED_STATE_DISABLEDandCOMPONENT_ENABLED_STATE_DEFAULTThe last one removes the setting, thereby restoring the component's state to whatever was set in it's manifest (or enabled, by default).
flags Optional behavior flags:DONT_KILL_APPor 0.

Viewpublic static intgenerateViewId()
Added in API level 17

  • 这简直是动态生成控件的福利啊,以后妈妈再也不用担心动态控件id冲突了。

Generate a value suitable for use insetId(int). This value will not collide with ID values generated at build time by aapt for R.id.

Returns
  • a generated ID value
ActivityManagerpublic booleanclearApplicationUserData()
Added in API level 19

  • 一键清除应用数据,不用再手动一个个clear了,但比较悲催的是API 19才提供的接口。

Permits an application to erase its own data from disk. This is equivalent to the user choosing to clear the app's data from within the device settings UI. It erases all dynamic data associated with the app -- its private data and data in its private area on external storage -- but does not remove the installed application itself, nor any OBB files.

Returns
  • trueif the application successfully requested that the application's data be erased;falseotherwise.
ActivityOptions
  • 不知道大家有没有注意到startActivity(Intent,Bundle),那么ActivityOptions就是这个Bundle的原型,负责Activity跳转时的动画。
[java] view plain copy
  1. ActivityOptionsopts=ActivityOptions.makeScaleUpAnimation(view,0,0,
  2. view.getWidth(),view.getHeight());
  3. //Requesttheactivitybestarted,usingthecustomanimationoptions.
  4. startActivity(newIntent(MainActivity.this,AnimationActivity.class),
  5. opts.toBundle());

Helper class for building an options Bundle that can be used with Context.startActivity(Intent, Bundle) and related methods.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值