Android develop tricks-some blogs from abroad, androidtricks

Source: Internet
Author: User

Android develop tricks-some blogs from abroad, androidtricks

ViewDragHelper-view dragging is a complicated problem. This class can help solve many problems. If you need an example, DrawerLayout uses it for slide. Flavient Laurent also wrote some excellent articles about this.

PopupWindow-Android uses PopupWindow everywhere, and you even don't realize it (Title navigation bar ActionBar, auto-completion AutoComplete, edit box error reminder Edittext Errors ). This class is the main method for creating the floating layer content.

Actionbar. getThemrContext () -- the topic of the navigation bar is very complex (different from the topic of other parts of the Activity ). You can get a Context. The custom component created using this Context can get the correct topic.

ThumbnailUtils -- help create a thumbnail. I usually use an existing image library (for example, Picasso or Volley), but this ThumbnaiUtils can create video thumbnails. Note: This API is only supported by V8.

Context. getExternalFilesDir () ---- after applying for the write permission on the SD card, you can write data anywhere in the SD. It is more polite to write your data in a well-designed location. In this way, the data can be cleared in a timely manner, and a better user experience will be provided. In addition, you do not need permissions to write data in this folder in Android 4.0 Kitkat. each user has its own independent data storage path. Note: This API is only supported by V8.

SparseArray -- efficient and optimized version of Map. We recommend that you understand SparseBooleanArray, SparseIntArray, and SparseLongArray.

PackageManager. setComponentEnabledSetting () -- can be used to start or disable components in the program list. It is very nice to disable unnecessary function components, such as disabling a broadcast receiver that is currently not used.

SQLiteDatabase. yieldIfContendedSafely () -- let you stop a Database Transaction temporarily, so that you can not occupy too much system resources.

Environment. getExternalStoragePublicDirectory () -- in that case, the user expects a unified user experience on the SD card. This method can be used to obtain the correct directory for storing specified types of files (such as music and images) on your device.

View. generateViewId () -- I want to recommend dynamically generate the Control ID every time. Note that it is not the same as the existing control ID or other generated control IDs.

ActivityManager. clearApplicationUserData () -- one-click cleaning of user data generated by your app may be the easiest way to log out.

Context. createConfigurationContext () -- customize your configuration environment information. I usually encounter the following problem: force a part to be displayed in a specific environment (it is not because I have been doing this all the time and it is hard for you to understand ). This can be a little simpler.

ActivityOptions -- easily define the animation for switching between two activities. ActivityOptionsCompat can solve the compatibility problem of the old version.

AdapterViewFlipper. fyiWillBeAdvancedByHostKThx () -- it's just for fun and no other reason. There are other interesting things (such
GRAVITY_DEATH_STAR_ I ). However, this is not the case. It does work.

ViewParent. requestDisallowInterceptTouchEvent () -- The Android system's touch event mechanism can be processed by default. However, sometimes you need to use this method to deprive the parent-level controls (by the way, if you want to learn more about the Android touch mechanism, this lecture will surprise you .)

Activity. isChangingConfigurations () -- if the configuration changes frequently in the Activity, you do not need to manually Save the status using this method.

SearchRecentSuggestionsProvider -- it is a simple and fast method to create a provider with the latest prompts.

ViewTreeObserver -- this is a great tool. You can enter the VIew and monitor the various states of the View structure. I usually use the View measurement operation (usually used in custom views ).

Org. gradle. daemon = true -- this statement can help reduce the time for Gradle building and is only used in command line compilation, because Android Studio is already used in this way.

DatabaseUtils-A Tool for using various database operations.

Android: weightSum (LinearLayout) -- if you want to use layout weights but do not want to fill the entire LinearLayout, you can use weightSum to define the total weight size.

Android: duplicateParentState (View) -- This method allows the child View to copy the state of the parent View. For example, if a ViewGroup is clickable, you can use this method to change its subview state when it is clicked.

Android: clipChildren (ViewGroup) -- if this attribute is set to unavailable, the Child View of the ViewGroup will be out of its range during painting and will be used for animation.

Android: fillViewport (ScrollView)-This article provides a detailed description of the article link, which can solve the problem of filling in the screen when the content in ScrollView is insufficient.

Android: tileMode (BitmapDrawable) -- you can specify the repeated filling mode for images.

Android: enterFadeDuration/android: exitFadeDuration (Drawables) -- this attribute defines the fade-in and fade-out effect before a Drawable has multiple States.

Android: scaleType (ImageView)-defines how to scale/crop images in ImageView. Generally, "centerCrop" and "centerInside" are used ".

Merge -- this label can contain other layout files in another layout file, instead of creating a new ViewGroup, which is also required for custom ViewGroup; you can automatically define its child parts by loading a layout file with tags.

AtomicFile-perform atomic operations on files by using backup files. I have written this knowledge point before, but it is better to have an official version.

UrlQuerySanitizer-this tool can be used to conveniently check URLs.

Fragment. setArguments -- this is a good thing because parameters cannot be added when building Fragment, you can set parameters before creating Fragment (even if the configuration changes, it will still cause destruction/reconstruction ).

DialogFragment. setShowsDialog () -- this is a clever way. DialogFragment can be displayed as a normal Fragment! Here, Fragment can undertake dual tasks. I usually add onCreateView () and onCreateDialog () when creating Fragment to create a Fragment with a dual purpose.

FragmentManager. enableDebugLogging () -- it will help you observe the Fragment status.

LocalBroadcastManager-this is safer, simpler, and faster than global broadcast. The Event buses mechanism like otto is more useful for your application scenarios.

PhoneNumberUtils. formatNumber () -- as the name suggests, this is used to format a number.

Region. op () -- I found it useful to compare the two regions before rendering. If you have two paths, how do you know if they overlap? This method can be used.

Application. registerActivityLifecycleCallbacks -- although it lacks official documentation, I think it is a convenient tool to register some callback methods (as the name suggests) for the Activity lifecycle.

VersionNameSuffix -- This gradle setting allows you to modify the attribute of the version name in the manifest Based on Different build types. For example, if you need to end with "-SNAPSHOT" in the debug version, you can easily see whether the current version is debug or release.

CursorJoiner -- if you use only one database, you can use join in SQL. However, if the received data comes from two independent contentproviders, CursorJoiner is very useful.

Genymotion-a very fast Android simulator I have been using.

-Nodpi-many modifiers (-mdpi,-hdpi,-xdpi, etc.) are automatically scaled to assets/dimensions by default without special definitions. Sometimes we need to keep the display consistent, in this case, you can use-nodpi.

BroadcastRecevier. setDebugUnregister ()-another convenient debugging tool.

Activity. recreate () -- force the Activity to be rebuilt.

PackageManager. checkSignatures () -- if two apps are installed at the same time, you can use this method to check. If you do not perform a signature check, others can easily use the same package name to imitate your app.

DateUtils.formatDateTime()It is used to format the region and output the time or date of formatting and localization.

AlarmManager.setInexactRepeatingUsing the alarm group method to save power, even if you only call one alarm, this is also a good choice (you can ensure that AlarmManager. cancel () is automatically called when use is complete (). In the original article, the description is abstract. Here we will describe in detail: setInexactRepeating refers to setting an inaccurate alarm clock. The usage is as follows: alarmManager. setInexactRepeating (AlarmManager. RTC, startTime, intervalL, pendingIntent), an inaccurate alarm can only ensure the approximate time interval, but not necessarily accurate. It may be set to 30 minutes, but the actual interval is 20 minutes, the other interval is 40 minutes. Its biggest advantage is that it can merge alarm events, such as setting intervals every 30 minutes without waking up sleep. after 8 hours of sleep, it has accumulated 16 alarm events, when a mobile phone is awakened, 16 events can be merged into a non-punctual alarm, so it seems that the non-punctual alarm is generally less energy-saving.

Formatter.formatFileSize()A regionalized file size formatting tool. In general, it is to convert the size to strings such as MB, G, and KB.

ActionBar.hide()/.show()As the name suggests, hiding and displaying ActionBar can elegantly convert between full screen and with Actionbar.

Linkify.addLinks()Add a link to Text. Very practical.

StaticLayoutIt is useful when rendering text in a custom View.

Activity.onBackPressed()It is very convenient to manage the back key. You can rewrite it when you need to control the events of the back key. For example, the "two-click back to exit" function is added.

GestureDetectorIt is used to listen to corresponding gesture events, such as clicks, long-pressed, slow slides, and fast slides. It is easy to use and much easier to implement than you do.

DrawFilterThis allows you to operate the canvas without calling the onDrew method. For example, you can set a DrawFilter when creating a custom View, set the anti-alias for all views in the parent View.

ActivityManager.getMemoryClass()It tells you how much memory your machine has and will be useful when calculating the cache size.

ViewStubIt is a View that does not do anything during initialization, but can then load a layout file. It is suitable for placeholders in slow loading views. The only drawback is that tags are not supported. Therefore, if you are not careful, unnecessary nesting may be added to the view structure.

SystemClock.sleep()This method is convenient to ensure sleep for a certain period of time. It is usually used for debugging and simulating network latency.

DisplayMetrics.densityIn this way, you can obtain the pixel density of the device. Most of the time, it is best for the system to automatically scale resources and other operations, but sometimes the control effect will be better. (especially when customizing a View ).

Pair.create()This facilitates the construction of classes and constructors.

Activity.startActivities()It is often used to start other activities in the middle of the application.

TextUtils.isEmpty()Simple tool class for checking whether it is empty

Html.fromHtml()Used to generate an Html. The parameter can be a string. I personally think it is not very fast, so I don't often use it. (I said it is not often used to highlight this sentence: Please manually build a Spannable to replace Html. fromHtml), but it is very good for rendering the text obtained from the web.

TextView.setError()Great for verifying user input

Build.VERSION_CODESThis indicates the current version number, which is often used to handle compatibility issues. Click here to see different features of each version.

Log.getStackTraceString()Convenient Log tool and method Log. v (), Log. d (), Log. I (), Log. w () and Log. e () Prints information to LogCat. Sometimes, you need to insert the error information to the database or a custom log file, in this case, the error message must be returned as a String, that is, when the static String getStackTraceString (Throwable tr) method is used.

LayoutInflater.from()As the name suggests, it is used for Inflate a layout. The parameter is the id of layout. Many people often write Adapter.

ViewConfiguration.getScaledTouchSlop()Use the values provided in ViewConfiguration to ensure that all touch interactions are consistent. The value obtained by this method indicates that the sliding is performed only after the distance of the user's hand sliding. of course, this value can also be determined by yourself. however, for consistency, the standard value is better.

PhoneNumberUtils.convertKeypadLettersToDigitsAs the name suggests, it is similar to the T9 Input Method to convert letters into numbers,

Context.getCacheDir()The path for obtaining the cached data folder is very simple, but few people know it. This path is usually on the SD card (the SD card here refers to the SD card in a broad sense, including external storage and internal storage) adnroid/data/your application package name/cache. during the test, you can check whether the cache is successful. the advantage of caching here is that you do not need to manually create folders on your own, and you do not have to worry about deleting the folders you have created. The files will be cleared when the application is uninstalled, third-party cleanup tools will also be cleared here.

ArgbEvaluatorUsed to process the gradient of a color. As Chris Banes said, this class performs a lot of automatic packing operations, so it is best to remove its logic and implement it by yourself. This has never been used. I don't know why. I will try again later.

ContextThemeWrapperIt is convenient to modify the topic during running.

SpaceSpace is a new control added in Android 4.0. It can be used to separate different controls and form a blank area. this is a lightweight view component that can skip Draw and is great for any scenario that requires placeholders.

ValueAnimator.reverse()This method can smoothly cancel running animations.



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.