1. Color transparency calculation

If the UI in the design is colored like this
#FF0000 (10% opacity), it is necessary to calculate the color transparency.

#

  • RGB: Red, Green, Blue
  • ARGB: Transparency (Alpha), Red, Green, Blue

Such as
#FF99CC00: FF is transparency, 99 is red, CC is green, 00 is blue

  • Transparency is divided into 256 levels, corresponding to 0~255

For example, transparency = order 0, 50% transparency = order 127, opacity = order 255

  • On the computer, it corresponds to the hexadecimal 00~FF
  • Transparency + Opacity =100%

For example, 10% opacity means 90% opacity

#FFFFFF (40% opacity)

  • If given transparency, first convert transparency to opacity, i.e. 60% opacity
  • The opacity255, or 40%255 = 153
  • Convert the calculation to hexadecimal, that is, the hexadecimal of 153 is 99
  • Finally concatenated into ARGB format, that is, the final color value:#99FFFFFF



2. SpannableString class

Sometimes, in order to make the text displayed in a TextView look and stand out, you may want to set different sizes or colors for the text displayed in a TextView. The clumsy way is to set up multiple TextViews separately. The clever way is to use SpannableString, a rich text tool introduced in this section.

Method a.

SetSpan (Object what, int start, int end, int flags)Copy the code
  • What: Text formats such as foreground, underline, blur, hyperlink, etc.
    • ForegroundColorSpanForeground &BackgroundColorSpanThe background color
    • RelativeSizeSpanRelative size &AbsoluteSizeSpanAbsolute size (pixels, px)
    • StrikethroughSpanIn the line &UnderlineSpanThe underline
    • SuperscriptSpanSuperscript &SubscriptSpanThe subscript
    • StyleSpanBold can be setnew StyleSpan(Typeface.BOLD)And in italicsnew StyleSpan(Typeface.ITALIC)
  • Start: the start index of the string to be formatted
  • End: indicates the end index of the string to be formatted
  • Flags: symbol to indicate whether start and end are included[]The symbol includes()Four attributes are not included:
    • Spanned.SPAN_INCLUSIVE_EXCLUSIVE: [start subscript, end subscript]
    • Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(start subscript, end subscript)
    • Spanned.SPAN_INCLUSIVE_INCLUSIVE: [start subscript, end subscript]
    • Spanned.SPAN_EXCLUSIVE_INCLUSIVE(start subscript, end subscript)

SpannableString displays those effects you should know about
https://blog.csdn.net/u012551350/article/details/51722893
B. the sample
https://www.jianshu.com/p/7b9abda70c8f

                                    XML <string name="total"> total %1$d $</string>
                                    // Set the amount color to white, Public void setTotalText(int total) {SpannableString SpannableString = new SpannableString(getResources().getString(R.string.total, total)); ForegroundColorSpan color = new ForegroundColorSpan(Color.parseColor("#FFFFFF")); spannableString.setSpan(color, 2, 2 + String.valueOf(total).length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); spannableString.setSpan(new AbsoluteSizeSpan(36), 2, 2 + String.valueOf(total).length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE); mTotalText.setText(spannableString); }
                                        
                                            
                                            Copy the code

3. Three ways to quickly switch to the main thread to update the UI


A:
Activity.runOnUiThread(Runnable)
Activity.runOnUiThread()

  • If the current thread is a UI thread, it will execute immediately
  • Otherwise, the UI thread is calledhandler.post()Put it in the message queue of the UI thread
New Thread(){public void run() {// The child Thread((MainActivity) context).runonuithRead (new Runnable() {@override public void Run () {return to MainActivity}}); }; }.start();Copy the code

B:
View.post(Runnable)

  • If the View is attached to the Window, call the UI thread’s Handler directly and send the Runnable to MessageQueue
  • If the View is not attached to the Window and the Runnable is added to the ViewRootImpl RunQueue, the RunQueue will delay the execution of the Runnable task and the Runnable will not be added to the MessageQueue. It will not be executed by Looper, but will wait until the next performTraversals of the View wrootimpl to remove all Runnable from the RunQueue and execute it, then clear the RunQueue
Mtextview.post (new Runnable() {@override public void run() {mtextView.settext (" XXX "); / / can also update other view mIageView. SetBackgroundResource (R.d rawable. The icon). }});Copy the code

View.postDelayed(Runnable, long)

//5 seconds countdown to the next page index=5; mTextView.postDelayed(new Runnable() { @Override public void run() { mTextView.setText("" + index); index--; if (index == 0) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } else { mTextView.postDelayed(this, 1000); }}}, 1000);Copy the code

Handler.post(Runnable)
Handler.post(Runnable,long)
The point extracting | message mechanism of art development
https://www.jianshu.com/p/1c79fb5296b6

                                                            // Assume that in the child thread, Looper and Queuenew Handler(looper.getMainLooper ()).post(new Runnable() {@override public void run() }});
                                                                
                                                            
                                                            Copy the code

https://www.jianshu.com/p/ab77a2e83c52

4. RecycleView item animation

Moment before online UI want to adjust the Animation again, because RecycleView itself to the item set up some Animation effects of add and remove, if you want to custom will need to rewrite some of the methods, the key points before refining | development introduced Android three kinds of Animation art of Animation,
https://www.jianshu.com/p/10dc575896d3), so it is more or less the same, here is a small example of adding a custom animation to understand.

@override protected void preAnimateAddImpl(recyclerView.viewholder holder) { Here in the center of the item to enlarge anchor holder. ItemView. SetPivotX (holder. ItemView. GetWidth () / 2); holder.itemView.setPivotY(holder.itemView.getHeight() / 2); holder.itemView.setAlpha(0); } // Set the animation magnification effect, here the effect is first enlarged 1.2 times and then reduced to the original, @override protected void animateAddImpl(Final RecyclerView.ViewHolder holder) {final DefaultAddVpaListener listener = new DefaultAddVpaListener(holder); Viewcompat.animate (holder.itemView)// Activate an animation for the current item. ScaleX (1.2f)//x 1.2x. ScaleY (1.2f)// Y 1.2x .setduration (300)// animation duration 300ms. Alpha (1)// animation end is completely opaque. SetInterpolator (mInterpolator)// setInterpolator.setlistener (new ViewPropertyAnimatorListener () {/ / set animation listener, Including animation start, end, and cancel the @ Override public void onAnimationStart View (View) {listener. OnAnimationStart (View); } @override public void onAnimationEnd(View View) { Viewcompat.animate (holder.itemView).scalex (1f).scaley (1f).setDuration(200)// Animation duration 200ms .setInterpolator(mInterpolator) .setListener(new ViewPropertyAnimatorListener(){ @Override public void onAnimationStart(View view) { listener.onAnimationStart(view); } @Override public void onAnimationEnd(View view) { listener.onAnimationEnd(view); } @Override public void onAnimationCancel(View view) { listener.onAnimationCancel(view); }}).setStartDelay(300).start(); } @Override public void onAnimationCancel(View view) { listener.onAnimationCancel(view); } }) .start(); // Start animation}Copy the code


https://blog.csdn.net/superbiglw/article/details/53392877

5. Use Rxjava to prevent click jitter

There was a bug mentioned in the previous test, which was caused by clicking Button quickly. I heard that my expression was as follows. In order to fully consider various habits of users, this operation was also crazy. The solution is to add anti-shake treatment to the button click, no matter how many times in a certain period of time are only called an event, here using Rxjava to achieve, article post Android Rxjava combat series: function anti-shake (
https://blog.csdn.net/uisoul/article/details/79114856).


public abstract class OnMultiClickListener implements View.OnClickListener { public static final int MIN_CLICK_DELAY_TIME = 1000; private long lastClickTime = 0; @Override public void onClick(View v) { long currentTime = Calendar.getInstance().getTimeInMillis(); if (currentTime - lastClickTime > MIN_CLICK_DELAY_TIME) { lastClickTime = currentTime; onMultiClick(v); } } public abstract void onMultiClick(View v); // Click the event}Copy the code

6.Java basic exception mechanism

When a program goes wrong, there are three possible errors:

  • Syntax errors: Such as the lack of necessary punctuation marks, keyword input errors, data type mismatch, etc. During the process of compiling the program, the compiler will list the detected syntax errors as prompts, so they are also called compilation errors.
  • Runtime errors: such as null pointer exception, array out of bounds, divisor zero, database connection failure, etc., forcing the program to terminate, with specific conditions.
  • Logic error: syntactically valid, but logically incorrect. This kind of problem is not easy to debug.


A. Terrable Inheritance hierarchy

  • ErrorError: An exception that cannot be recovered by the program, indicating a serious problem in running the application.
    • Occurs when the virtual machine itself or when the virtual machine attempts to execute an application, such asVirtual MachineError(Java VM running error),NoClassDefFoundErrorClass definition error.
    • It is an untraceable exception, that is, it does not force the programmer to handle it, and even if it does not handle it, syntax errors will not occur.
  • ExceptionException: Indicates the exception that can be recovered by the program. There are two main categories:
    • Exceptions other than RuntimeException, such asFileNotFoundException(The file is normal.)
    • Is a traceable exception that forces the programmer to handle it, or a syntax error occurs if it is not handled.
    • NullPointerException(null pointer exception),IndexOutOfBoundsException(subscript out-of-bounds exception).
    • Belongs to an untraceable exception.
    • RuntimeExceptionRuntime exception: An exception caused by a problem in the program itself.
    • Non-runtime exception: An exception caused by a problem outside the program.



B. Exception handling mechanism

  • tryCatch exception: Used to monitor, if an exception occurs, the object generated by the exception class is thrown and execution immediately ends, and the catch block is turned to exception handling.
  • catchHandling exceptions: If the exception object thrown is an exception class defined ina catch, the program continues to run in the corresponding section of the catch, or in the finally block. Common methods:
    • e.getMessage(): returns a short description of the exception object
    • e.toString(): Gets details about the exception object
    • e.printStackTrace(): Prints the exception object and its trace information on the console
  • finallyFinal processing: Statements ina finally block are executed whether or not exceptions are caught or handled. A finally block is not executed in four special cases:
    • An exception occurred in the finally statement block
    • I used it in the previous codeSystem.exit()Exit the program
    • The thread on which the program resides dies
    • Shut down the CPU
Type1} catch (Type1) {// catch (Type2) {// catch (Type2)} finally {// Block of statements that will be executed whether or not an exception occurs}Copy the code

Note:

  • No other code can be inserted between a try, catch, and finally
  • There can be more than one catch, and only one try and finally
  • A try must be followed by at least one of the catch and finally
  • throws: Declares the exception thrown after the method name and before the exception type
  • throw: Throws an exception, usually inside the method body
  • Declare a custom Exception class and inherit Exception, overriding methods likegetMessage()
  • In the method headthrowsDeclare exceptions that the method may throw
  • Create a custom exception class object in the appropriate place in the method body and usethrowThrow an exception
  • When this method is called, exceptions that might arise are caught and handled
Class MyException extends Exception {String message; public MyException(String ErrorMessagr) { super(ErrorMessagr) ; } public String getMessage() { return message; }}public class Demo { public static void main(String[] args) { //4. Catch and handle try {test() when calling a method; } catch (MyException e) { System.out.println(e.getMessage()); e.printStackTrace(); Public static void test() throws MyException{try {int I = 10/0; System.out.println("i="+i); } catch (ArithmeticException e) { //3. Throw new MyException("This is MyException") if appropriate; }}}Copy the code

https://www.cnblogs.com/liaoliao/p/5009150.html

7. A little insight









Recent Articles:

  • Funny diagrams that only programmers can understand

  • Learn these 3 Android Studio operations, save you a double monthly salary

  • 3 minutes to get to the bottom of generics

Question of the day:

Do you have any friends from Meituan?

Exclusive upgrade community: I Finally Figured it out