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 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)來讓開發者自定義錯誤提示圖片。
效果圖:

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



    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.   
    3. <selector xmlns:android="http://schemas.android.com/apk/res/android"  
    4.     android:enterFadeDuration="500"  
    5.     android:exitFadeDuration="500">  
    6.   
    7.     <item android:state_focused="true"  
    8.         android:drawable="@color/press"/>  
    9.     <item  
    10.         android:state_pressed="true"  
    11.         android:drawable="@color/press"/>  
    12.     <item  
    13.         android:drawable="@color/normal"/>  
    14. </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 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, 00,  
    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.



    注意!

    本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



     
    粤ICP备14056181号  © 2014-2021 ITdaan.com