Android开发中的小技巧

时间:2024-07-26 17:35:56

转自:http://blog.****.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 void startActivities (Intent[] intents)

Added in API level 11
  • 该方法和我们寻经常使用到的startActivity很相似,仅仅只是将Intent[]中的Intent所指向的跳转目标Activity从后往前依次加入到返回栈中。跳转完后假设按Back键的话会发现返回的顺序和Intent[]中的顺序前后一致。

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

Parameters
intents The intents to start.
Throws
  android.content.ActivityNotFoundException

public static boolean isEmpty (CharSequence str)

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 static Spanned fromHtml (String source)

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 void setError (CharSequence error)

Added in API level 1
  • 在TextView上不太经常使用,很多其它用在EditText上(EditText继承自TextView)提示用户输入非法。还有个多态方法setError(CharSequence error,Drawable icon)来让开发人员自己定义错误提示图片。
效果图:Android开发中的小技巧

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 the error is null, the error message and icon will be cleared.


public static String getStackTraceString (Throwable tr)

Added in API level 1
  • 有时候我们希望程序抛出异常时能把异常信息保存到制定文件夹的文件里,getStackTraceString就能够将异常信息转换成字符串的形式。
使用演示样例:
[java] view
plain
 copy
  1. try {
  2. //TODO
  3. } catch (Exception e) {
  4. String exceptionStr = Log.getStackTraceString(e);
  5. }

Handy function to get a loggable stack trace from a Throwable

Parameters
tr An exception to log

public static LayoutInflater from (Context context)

Added in API level 1
  • 和冗长的getSystemService()说Goodbye。

Obtains the LayoutInflater from the given context.

public abstract File getCacheDir ()

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 not rely on
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 void reverse ()

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 static String formatFileSize (Context context,
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

Linkify public static final boolean addLinks (TextView text,
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时遇到长串文字须要换行时用到

Activity public void onBackPressed ()

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 supplied MotionEvents.
The GestureDetector.OnGestureListener callback
will notify users when a particular motion event has occurred. This class should only be used with MotionEvents
reported via touch (don't use for trackball events). To use this class:                                                                                 

ActivityManager public int getMemoryClass ()

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.

SystemClock public static void sleep (long
ms)

Added in API level 1
  • 还在为測试网络延迟烦恼么?用这种方法能够非常方便的模拟网络延迟。并且不会抛出InterruptedException

Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long),
but does not throw InterruptedExceptioninterrupt() 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.density public float density

Added in API level 1
  • 常常使用DisplayMetrics来获取屏幕高度和宽度,此外,还能够通过它获取屏幕密度
[java] view
plain
 copy
  1. DisplayMetrics dm = new DisplayMetrics();
  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 by xdpi and ydpi,
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. UrlQuerySanitizer sanitizer = new UrlQuerySanitizer("http://example.com/?

    name=Mark");

  2. sanitizer.setAllowUnregisteredParamaters(true);
  3. String name = sanitizer.getValue("name");

Fragment public void setArguments (Bundle args)

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的范围仅仅是本应内,所以更有效率,更省资源

PhoneNumberUtils public static String formatNumber (String phoneNumber, String defaultCountryIso)

Added in API level 1
  • PhoneNumverUtils提供了一系列方法用来格式化电话号码
[java] view
plain
 copy
  1. String num = "031185203009";
  2. PhoneNumberUtils util = new PhoneNumberUtils();
  3. String numFormated =  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

Application public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)

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

Activity public void recreate ()

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 to onDestroy() and
a new instance then created after it.

PackageManager public abstract int checkSignatures (String pkg1, String pkg2)

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

Activity public boolean isChangingConfigurations ()

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 in onStop() to
determine whether the state needs to be cleaned up or will be passed on to the next instance of the activity via onRetainNonConfigurationInstance().

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 to getViewTreeObserver() 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 symbol weightSum.

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 symbol duplicateParentState.

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 symbol clipChildren.

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 symbol fillViewport.

android:tileMode

  • 用来设置Bitmap显示方式。有平铺、反复等。比如设置反复显示
[html] view
plain
 copy
  1. <xml version="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" />

Android开发中的小技巧




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 symbol tileMode.

android:enterFadeDuration/android:exitFadeDuration

Added in API level 11
  • 为selector设置渐变效果。演示样例:
[html] view
plain
 copy
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:enterFadeDuration="500"
  4. android:exitFadeDuration="500">
  5. <item android: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>

Android开发中的小技巧

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 symbol scaleType.

<merge>

PopupWindow

  • 在一些经经常使用到的控件中都能看到PopupWindow的身影。比方actionbar、autocompleteTextView等。PopupWindow可用于创建悬浮窗体

ThumbnailUtils

  • 能够非常方便的创建视频的缩略图。甚至还能够指定缩略图的尺寸
Public Constructors
ThumbnailUtils()
Public Methods
static Bitmap createVideoThumbnail(String filePath,
int kind)
Create a video thumbnail for a video.
static Bitmap extractThumbnail(Bitmap source,
int width, int height, int options)
Creates a centered bitmap of the desired size.
static Bitmap extractThumbnail(Bitmap source,
int width, int height)
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 using keyAt(int) and valueAt(int).
Iterating over the keys using keyAt(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 of valueAt(int).

PackageManger public abstract void setComponentEnabledSetting (ComponentName componentName,
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_ENABLEDCOMPONENT_ENABLED_STATE_DISABLED andCOMPONENT_ENABLED_STATE_DEFAULT The
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_APP or
0.

View public static int generateViewId ()

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

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

Returns
  • a generated ID value

ActivityManager public boolean clearApplicationUserData ()

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
  • true if the application successfully requested that the application's data be erased; false otherwise.

ActivityOptions

  • 不知道大家有没有注意到startActivity(Intent,Bundle),那么ActivityOptions就是这个Bundle的原型。负责Activity跳转时的动画。
[java] view
plain
 copy
  1. ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0,
  2. view.getWidth(), view.getHeight());
  3. // Request the activity be started, using the custom animation options.
  4. startActivity(new Intent(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.