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 usegetResources().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 -
Throwable
The method in the classgetStackTrace()
, according to this method, the layer-by-layer call address of the function can be obtained, and its return value isStackTraceElement[]
;StackTraceElement
the class, four of whichgetClassName()
,getFileName()
,getLineNumber()
,getMethodName()
are very useful when debugging the program to print the Log; -
TextUtils
It is a very useful tool class to convert List into string, comma-separated, comma-separated String string, cut into List,TextUtils
and methodsjoin
can be used respectively.split
If you want to deduplicate the List, you canCollection
usefrequency
the 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
isShown
the view itself and all of its ancestors arevisible
isShown()
TRUE
-
android:clipChildren
: Whether to limit the child View within its scope, the magical property -
You can get screenshots through it
View.getDrawingCache()
, butsetDrawingCacheEnabled(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" -
runOnUiThread
andview.post
are 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 Activity
onUserLeaveHint
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 classgetLocationOnScreen(int[])
to get the position of the View in the window/screen -
setSelected(boolean)
The methods in the View class are combinedandroid:state_selected=""
to achieve the picture selection effect -
StaticLayout
It 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 id
my_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;
}
tools
Tags 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 manifest
android: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.
Merge
This 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. -
ActivityOptions
Responsible 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().density
You can get the screen density without Context
- In the Fragment class ,
when usingadd()
+ 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)
FragmentPagerAdapter
ViewPager
onHiddenChanged()
setUserVisibleHint(boolean isVisibleToUser)
other
-
Messenger , the encapsulation of AIDL implementation, is more convenient than handwriting AIDL .
-
SparseArray
Efficient 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 width
and height
attributes, 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_content
styles 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.
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
2. Source code analysis collection
3. The collection of open source frameworks
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↓↓↓