您的位置:首页 > 移动开发 > Android开发

Android开发中的小技巧

2016-03-25 14:30 731 查看
转自:/article/8009277.html

简介:

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
intentsThe 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
strthe 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)来让开发者自定义错误提示图片。

效果图:


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

try {

//TODO

} catch (Exception e) {

String exceptionStr = Log.getStackTraceString(e);

}

Handy function to get a loggable stack trace from a Throwable

Parameters
trAn 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
contextContext to use to load the localized units
numbersize 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

可以将TextView中的文字根据设定的mask自动设置成超链接,设置超链接的点击事件时会用到LinkMovementMethod。我还用过,大家可参考这篇博文

Android应用实例之---使用Linkify
+ 正则式区分微博文本链接及跳转处理

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
MotionEvent
s.
The
GestureDetector.OnGestureListener
callback
will notify users when a particular motion event has occurred. This class should only be used with
MotionEvent
s
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
InterruptedException
;
interrupt()
events
are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.

Parameters
msto 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

DisplayMetrics dm = new DisplayMetrics();

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

UrlQuerySanitizer sanitizer = new UrlQuerySanitizer("http://example.com/?name=Mark");

sanitizer.setAllowUnregisteredParamaters(true);

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

String num = "031185203009";

PhoneNumberUtils util = new PhoneNumberUtils();

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
sourceThe 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
pkg1First package name whose signature will be compared.
pkg2Second package name whose signature will be compared.
Returns

Returns an integer indicating whether all signatures on the two packages match. The value is >= 0 (
SIGNATURE_MATCH
)
if all signatures match or < 0 if there is not a match (
SIGNATURE_NO_MATCH
or
SIGNATURE_UNKNOWN_PACKAGE
).


Activity public boolean isChangingConfigurations ()

Added in API level 11

常用于屏幕方法改变时的逻辑处理,但我还没用到过,所以详细介绍还是挪步到

Activity.isChangingConfigurations()

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

setClipChildren(boolean)


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

<xml version="1.0" encoding="utf-8"?>

<LinearLayout

android:id="@+id/MainLayout"

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical"

android:background="@drawable/backrepeat"

>

backrepeat.xml

[html] view
plain copy

<bitmap

xmlns:android="http://schemas.android.com/apk/res/android"

android:src="@drawable/repeatimg"

android:tileMode="repeat"

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.
ConstantValueDescription
disabled
-1Do not tile the bitmap. This is the default value.
clamp
0Replicates the edge color.
repeat
1Repeats the bitmap in both direction.
mirror
2Repeats 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

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android"

android:enterFadeDuration="500"

android:exitFadeDuration="500">

<item android:state_focused="true"

android:drawable="@color/press"/>

<item

android:state_pressed="true"

android:drawable="@color/press"/>

<item

android:drawable="@color/normal"/>

</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

经常用到的设置图片在ImageView中的展示样式。参考示例请挪步:ImageView.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.
ConstantValueDescription
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>

在某些情况下可以优化UI结构,删除多余层级。但个人感觉使用情景有些局限。使用详情见:


Android
Layout Tricks #3: Optimize by merging


PopupWindow

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


ThumbnailUtils

可以很方便的创建视频的缩略图,甚至还可以指定缩略图的尺寸

Public Constructors
ThumbnailUtils()
Public Methods
static BitmapcreateVideoThumbnail(String filePath,
int kind)
Create a video thumbnail for a video.
static BitmapextractThumbnail(Bitmap source,
int width, int height, int options)
Creates a centered bitmap of the desired size.
static BitmapextractThumbnail(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
componentNameThe component to enable
newStateThe new enabled state for the component. The legal values for this state are:
COMPONENT_ENABLED_STATE_ENABLED
,
COMPONENT_ENABLED_STATE_DISABLED
and
COMPONENT_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).
flagsOptional 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

ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0,

view.getWidth(), view.getHeight());

// Request the activity be started, using the custom animation options.

startActivity(new Intent(MainActivity.this, AnimationActivity.class),

opts.toBundle());

Helper class for building an options Bundle that can be used with
Context.startActivity(Intent,
Bundle)
and related methods.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: