Practical tips for android development

string correlation

  • To format a string, you can use format(String,Object…)the method of the String class. If you want to format the string in the resource file strings.xml, you can use getResources().getString(int,Object…)the method
String.format("money:¥%.2f",1.00);  
<resources>  
    <string name="format">money:$%.2f</string>  
</resources>  
getResources().getString(R.string.format,1.00); 
  • When there is % in the string, the parameter formatted is false<string name="citypartner_sz" formatted="false">%100</string>

  • For 11-digit mobile phone numbers, the space requirement is automatically added, just add the following listener
    mMobileEt.addTextChangedListener(new PhoneNumberFormattingTextWatcher(Locale.CHINA.getCountry()));

  • PhoneNumberUtils.formatNumber(num,"CN")format phone number

  • DateUtils.getRelativeTimeSpanString(long startTime)Returns a string in the format "a few days ago"/"xx days ago"

  • android.text.format.Formatter.formatFileSize(Context, long)method, used to format the file Size (B → KB → MB → GB);

  • Log.getStackTraceString(e)The exception information can be converted into a string

  • ThrowableThe method in the class getStackTrace(), according to this method, the layer-by-layer call address of the function can be obtained, and its return value is StackTraceElement[]; StackTraceElementthe class, four of which getClassName(), getFileName(), getLineNumber(), getMethodName()are very useful when debugging the program to print the Log;

  • TextUtilsIt is a very useful tool class to convert List into string, comma-separated, comma-separated String string, cut into List, TextUtilsand methodsjoin can be used respectively. splitIf you want to deduplicate the List, you can Collectionuse frequencythe method of .

  • Sort by pinyin

List<String> list = new ArrayList<>(Arrays.asList("翁", "啊", "好", "月"));
Log.d(TAG, "before sort: " + list);
Collections.sort(list, Collator.getInstance(Locale.SIMPLIFIED_CHINESE));

View related

  • ViewFlipper realizes the switching (cycle) of multiple views, can customize the animation effect, and can specify animation for a single switch, such as the display of winning information.

  • view method that returns only if isShownthe view itself and all of its ancestors arevisibleisShown()TRUE

  • android:clipChildren: Whether to limit the child View within its scope, the magical property

  • You can get screenshots through it View.getDrawingCache(), but setDrawingCacheEnabled(true)it may be oom if you need to use it frequently. There is another way to use it directlycanvasBitmap bm = Bitmap.createBitmap((int) (w * scale), (int) (h*scale), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(); canvas.setBitmap(bm);View.draw(canvas);return bm;

  • ArgbEvaluator.evaluate(float fraction, Object startValue, Object endValue);It is used to generate a new color based on a start color value, an end color value and an offset, and achieve a color gradient similar to the sliding color of the bottom bar of WeChat in minutes.

  • android:duplicateParentState="true", let the child View follow the state of its Parent, such as pressed, etc.

  • setError(CharSequence error,Drawable icon)Used to validate user input, usually used in EditText.

  • includeFontPadding="false", TextView has a certain amount of padding at the top and bottom by default. Sometimes we may not need to leave the top and bottom blank, just add it.

  • TextView.setCompoundDrawablePadding, the code sets the drawable padding of the TextView.

  • The method in the TextView class setTransformationMethod(TransformationMethod)can be used to realize the functions of "display password" and "display uppercase"

  • runOnUiThreadand view.postare both methods to return to the main thread directly, without writing a handler, and can be used to refresh ui-related operations.

  • android:descendantFocusability, when elements such as CheckBox in the item of the ListView grab the focus and cause the item click event to fail to respond, in addition to setting focusable for the corresponding element, it is easier to add it to the root layout of the itemandroid:descendantFocusability="blocksDescendants"

  • Three methods in the View class: callOnClick(),performClick(),performLongClick(), used to trigger the click event of the View ;

  • Rewrite the method of ActivityonUserLeaveHint to ensure that some tasks of the interface can be suspended immediately when the user leaves the interface

  • getLocationInWindow(int[])Methods and methods in the View class getLocationOnScreen(int[])to get the position of the View in the window/screen

  • setSelected(boolean)The methods in the View class are combined android:state_selected=""to achieve the picture selection effect

  • StaticLayoutIt is a tool class for processing text wrapping in android. StaticLayout has already implemented text drawing and wrapping processing. Generally, it is only used when a long string of text needs to wrap when customizing View

public void onDraw(Canvas canvas){
    
      
            super.onDraw(canvas);  
            TextPaint tp = new TextPaint();
            tp.setColor(Color.BLUE);
            tp.setStyle(Style.FILL);
            tp.setTextSize(50);
            String message = "这里是一个long long long long long long long long long long long long long text,自己看着换行显示吧,哈 哈";
            StaticLayout myStaticLayout = new StaticLayout(message, tp, canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            myStaticLayout.draw(canvas);
            canvas.restore();
 }  

  • generateViewId dynamically generates the control idmy_view.setId(View.generateViewId());

  • To save a view as a Bitmap, you can use the first method under normal circumstances, but if it is a ScrollView, you must use the second method

public Bitmap createViewBitmap(View v) {
    
      
    Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),  
            Bitmap.Config.ARGB_8888);  
    Canvas canvas = new Canvas(bitmap);  
    v.draw(canvas);  
    return bitmap;  
} 

  public static Bitmap getBitmapByView(ScrollView scrollView) {
    
    
        int h = 0;
        Bitmap bitmap = null;
        // 获取scrollview实际高度
        for (int i = 0; i < scrollView.getChildCount(); i++) {
    
    
            h += scrollView.getChildAt(i).getHeight();
            scrollView.getChildAt(i).setBackgroundColor(
                    Color.parseColor("#ffffff"));
        }
        // 创建对应大小的bitmap
        bitmap = Bitmap.createBitmap(scrollView.getWidth(), h,
                Bitmap.Config.RGB_565);
        final Canvas canvas = new Canvas(bitmap);
        scrollView.draw(canvas);
        return bitmap;
    }

  • toolsTags can help developers preview the effect of xml in real time, and the content of the tools tag will not be displayed after running. For example
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:text="这段话只在预览时能看到,运行以后就看不到了" />

AndroidManifest.xml

  • Oom has a lazy and effective solution, add to the manifestandroid:largeHeap="true"
  • After setting android:excludeFromRecents="true"the attribute for the Activity tag, after exiting the program, press and hold home, the Activity will not be displayed in the recent task list

resource

  • -nodpi——In the case of no special definition, many modifiers (-mdpi, -hdpi, -xdpi, etc.) will automatically scale assets/dimensions by default. Sometimes we need to keep the display consistent. In this case, we can use it -nodpi.
  • MergeThis tag can contain other layout files in another layout file without creating a new ViewGroup, which is also needed for custom ViewGroup; it can be automatically defined by loading a layout file with a tag part.

Component related

  • startActivities(android.content.Intent))It is often used to start other activities in the middle of the application.

  • Activity.recreate ()Forces the Activity to rebuild.

  • ActivityOptionsResponsible for the animation when the Activity jumps

ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(view, 0, 0,
            view.getWidth(), view.getHeight());
startActivity(new Intent(MainActivity.this, AnimationActivity.class),
            opts.toBundle());

  • Fragment.setArguments—Pass parameters to Fragment
  • The manager of the fragment nested inside the fragment is getChildFragmentManager()obtained by
  • DisplayMetrics to get the screen height and width, in addition, you can also get the screen density through it
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
//DisplayMetrics{density=3.0, width=1080, height=1920, scaledDensity=3.0, xdpi=428.625, ydpi=427.789}

Resources.getSystem().getDisplayMetrics().densityYou can get the screen density without Context

  • In the Fragment class ,
    when using add()+ to jump to a new Fragment, the old Fragment will call back and will not call back life cycle methods, while the new Fragment will not call back when it is created , and finally the View of the Fragment will not call life Cycle; when using + , when switching back to the previous Fragment page (already initialized), no lifecycle methods will be called back and only callbacks will be made, so if you want to do some lazy loading, you need to handle it here.show()hide()onHiddenChanged()onStop()onHiddenChanged()
    show()hide()setVisibility(true还是false)
    FragmentPagerAdapterViewPageronHiddenChanged()setUserVisibleHint(boolean isVisibleToUser)

other

  • Messenger , the encapsulation of AIDL implementation, is more convenient than handwriting AIDL .

  • SparseArrayEfficient optimized version of Map. It is recommended to understand the sister classes SparseBooleanArray, SparseIntArray and SparseLongArray

  • ActivityManager.getMemoryClass ()Through this method, you can know how much memory the system can allocate to the APP.

  • SystemClock.sleep (long)Using this method can easily simulate network delays without throwing InterruptedException

  • UrlQuerySanitizer is a very convenient tool class for processing url links

///取name值
UrlQuerySanitizer sanitizer = new UrlQuerySanitizer("http://xxx.com/?name=d");
sanitizer.setAllowUnregisteredParamaters(true);
String name = sanitizer.getValue("name");

style

Add a default layout style for your app, for example: each control needs to write widthand heightattributes, but many controls have the same width and height attributes wrap_content, then we can add the following styles in the style file, the width and height of the controls are all wrap_contentstyles by default La

<style name="Theme.YourApp" parent="android:style/Theme.Light">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
</style>

Gradle

  • versionNameSuffix allows you to modify the version name attribute 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 it is the debug version or the release version

Version

  • .gitignore can only ignore those files that were not originally tracked. If some files have been included in version management, modifying .gitignore is invalid. Then the solution is to delete the local cache first (change it to an untracked state), and then submit:
git rm -r --cached .
git add .
git commit -m 'update .gitignore'
  • When the locally generated git library is to be submitted to remote, pull reports _fatal: refusing to merge unrelated histories_git pull origin master --allow-unrelated-histories

at last

If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.

If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
insert image description here
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.

Full set of video materials:

1. Interview collection

insert image description here
2. Source code analysis collection
insert image description here

3. The collection of open source frameworks
insert image description here
welcomes everyone to support with one click and three links. If you need the information in the article, directly scan the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓

Guess you like

Origin blog.csdn.net/weixin_43440181/article/details/130017023