The article directories

    • I. Project related analysis (various files, resource access)
          • 1. Introduction to res resource folder:
          • 2. How to use these resources
        • Three important files mainActivity.java layout file: acticity_main.xml Android configuration file AndroidMainfest.xml
    • 2. Event-based monitoring mechanism
        • 1. Time processing mechanism model based on monitoring
        • 2. Five different uses (listening)
          • 1) Use anonymous inner classes directly
          • 2) Use inner classes
          • 3) Use external classes
          • 4) Use the Activity directly as a time listener
          • 5) Bind directly to the tag
        • 3. Event handling mechanism based on callback
          • 1. What is a method callback?
          • 2.Android callback event handling mechanism
            • 1) Customize the View
            • 2) Event propagation based on callback:
        • 4. Brief analysis of the message transmission mechanism of Handler
        • 5.TouchListener PK OnTouchEvent + Multi-touch
          • 1. TouchListener based on listener
          • 2. Callback based onTouchEvent() method
          • 3. Multi-touch
        • 6. Listen for content changes in the EditText
          • 1. Listen for changes in the EditText
          • 2. Make passwords visible and invisible in EditText
        • 7. Events that respond to system Settings (Configuration class)
          • Configuration gives us a list of methods
        • 8.AsyncTask Asynchronous tasks
        • 9. Gestures (Gestures)
          • 1. The execution order of gesture interaction in Android
    • conclusion

I. Project related analysis (various files, resource access)

Java: Where we write Our Java code, where our business functions are implemented res: where we store our various resource files, images, strings, animations, audio, etc., and various forms of XML files

1. Introduction to res resource folder:

All resource files will generate the corresponding resource ID under the R.java file, we can directly access the corresponding resource through the resource ID. Using Mipmap will provide certain performance optimization in image scaling. The system will select the corresponding images under HDPI, MDPI, XMDPI and xxHDPI according to the screen resolution. Therefore, when you unzip someone’s APK, you can see the images under the same name as the above directories, in all four folders. Just different sizes and pixels! Of course, this is not absolute, for example, if we drop all the images in the drawable- hdPI folder, even if the phone should load the image resources in the LDPI folder, but not in the LDPI folder, then it will still load the images in the HDPI folder! In addition, there is another case: for example, hdPI, MDPI directory has, ldPI does not, then will load mdPI resources! The principle is to use the closest density level! In addition, if you want to disable Android from loading different folder resources without following the screen density, simply add the Android :anyDensity=”false” field to the androidmanifest.xml file.



1. Picture resources

Drawable: Store various bitmap files (.png,.jpg,.9png,.gif, etc.) in addition to some other drawable XML files

Mipmap-hdpi: High resolution, usually put files here

Mipmap-mdpi: Medium resolution, very little unless compatible with the phone for a long time

Mipmap-xhhdpi: Ultra high resolution, mobile phone screen material is getting better and better, will gradually move to this.

Mipmap-xxhdpi: Super high resolution, high-end machine can be used

Mipmap-xxhdpi: Super super super high resolution, cow

2. Layout resources Layout: This directory is where our layout files are stored. In addition, for some specific models, we will create another set of layout, such as layout-480320 folder, for screen adaptation

3. Menu resources (none) Menu: It is often used on mobile phones with physical menu buttons, that is, menu key. Resource XML related to menu items can be compiled here

4. Values directory colors. XML: defines color resources string. XML: defines string resources styles. XML: defines style resources

5. The raw directory (none) is used to store all kinds of native resources (audio, video, some XML files, etc.), we can use openRawResource(int ID) to get the binary stream of resources! In fact, it is similar to Assets, except that the Assets in the R file will generate a resource ID 6. And finally, there are two kinds of animations: animator: the XML file that holds the property animation and anim: the XML file that holds the tween animation

2. How to use these resources

All of our resource files generate a resource ID under the R.Java file. We can access the resource using this resource ID in two ways: Java code and XML code.

In Java code:

Text: txtName setText (getResources (). The getText (R.s tring. Name)); Images: imgIcon. SetBackgroundDrawableResources (R.d rawable. Icon). Color: txtName setTextColor (getResources (). The getColor (R.c olor. Red)); Layout: the setContentView (R.l ayout. Main); Control: txtName = (TextView) the findViewById (R.i which xt_name);

XML code using: @ XXX can be obtained, such as here to get text and images :\

Three important files mainActivity.java layout file: acticity_main.xml Android configuration file AndroidMainfest.xml

Mainactivity.java: the code is as follows: Package jay.com.example.firstapp.mainactivity.java:

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

}

Code analysis:



Layout file: activity_main.xml:

The code is: \

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />
Copy the code

Code analysis:



Androidmanifest.xml configuration file:

The code is as follows:

<? The XML version = “1.0” encoding = “utf-8”? >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
Copy the code

Code analysis:! [insert picture description here] (img – blog. Csdnimg. Cn / 20210207150…).

I’m going to be pissed off by android Studio’s UI layout

2. Event-based monitoring mechanism

1. Time processing mechanism model based on monitoring



Written expression:

The event monitoring mechanism consists of event source, event and event listener. The processing flow is as follows: Step 1: set a listener for an event source (component), which is used to listen to user operations. Step 2: The user’s operation triggers the listener of the event source. Step 3: generates the corresponding event object 5: Event listener to judge the event object, execute the corresponding event handler (corresponding event processing method)

Conclusion:

Event listener mechanism is a delegating event processing mechanism. Event source (component) event processing is entrusted to event listener. When the event source occurs the specified event, the specified event listener will be notified and the corresponding operation will be performed

2. Five different uses (listening)

We use the following: simple button click, prompt Toast information program; Use five different forms to implement!

Effect:

1) Use anonymous inner classes directly

Usually the most commonly used one: directly setXxxListener, rewrite the inside of the method can be; Usually temporary use once, reuse is not high!

public class MainActivity extends Activity {    
    private Button btnshow;    
        
    @Override    
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main);    
        btnshow = (Button) findViewById(R.id.btnshow);    
        btnshow.setOnClickListener(new OnClickListener() {    
            // Override the click event handler onClick()
            @Override    
            public void onClick(View v) {    
                // Display Toast information
                Toast.makeText(getApplicationContext(), "You clicked the button.", Toast.LENGTH_SHORT).show(); }}); }}Copy the code
2) Use inner classes
public class MainActivity extends Activity {    
    private Button btnshow;    
    @Override    
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main); 
     // Use an inner class
        button2=findViewById(R.id.button2);
        // Directly new an inner class as an object
        button2.setOnClickListener(new BtnClickListener());
    }
    // Define an inner class that implements the view.onClickListener interface and override the onClick() method
    class BtnClickListener implements View.OnClickListener{

        @Override
        public void onClick(View v){
              Toast.makeText(getApplicationContext(),"The button was clicked.",Toast.LENGTH_SHORT).show(); }}}Copy the code
3) Use external classes

Create another Java file to handle events. This form is rarely used! Because external classes cannot directly access components in user interface classes, they are passed in for use through constructors; The result is code that isn’t very clean!

Myclick.java:

package com.jay.example.innerlisten;    
    
import android.view.View;    
import android.view.View.OnClickListener;    
import android.widget.TextView;    
    
public class MyClick implements OnClickListener {    
    private TextView textshow;    
    // Pass the text box as an argument
    public MyClick(TextView txt)    
    {    
        textshow = txt;    
    }    
    @Override    
    public void onClick(View v) {    
        // Click to set the text displayed in the text box
        textshow.setText("Click the button!");    
    }    
Copy the code

MainActivity.java

public class MainActivity extends AppCompatActivity {
    TextView textView3;
    Button button3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Use an external class
        button3=findViewById(R.id.button3);
        textView3=findViewById(R.id.tex3);
        button3.setOnClickListener(newMyClick(textView3)); }}Copy the code
4) Use the Activity directly as a time listener

Simply have the Activity class implement the XxxListener event listener interface and define and override the corresponding event handler methods in the Activity Eg :Actitity implements the OnClickListener interface, which overwrites the onClick(View) method to add the event Listener object for certain components by directly setxxx. Listener(this)

The implementation code is as follows: mainacivity.java


package com.jay.example.innerlisten;    
import android.os.Bundle;    
import android.view.View;    
import android.view.View.OnClickListener;    
import android.widget.Button;    
import android.widget.Toast;    
import android.app.Activity;    
    
// Let the Activity method implement the OnClickListener interface
public class MainActivity extends Activity implements OnClickListener{    
    private Button btnshow;    
    @Override    
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main);    
            
        btnshow = (Button) findViewById(R.id.btnshow);    
        // Just write this
        btnshow.setOnClickListener(this);    
    }    
    // Override abstract methods in the interface
    @Override    
    public void onClick(View v) {    
        Toast.makeText(getApplicationContext(), "Clicked the button using the Activity", Toast.LENGTH_SHORT).show(); }}Copy the code
5) Bind directly to the tag

In the XML layout file, you define an event handler for the Activity that is due. Eg :public void myClick(View source) Source corresponds to the event source (component). Then in the layout file, you set a property onclick for the component that is to trigger the event = “myclick”

The implementation code is as follows: mainacivity.java

package com.jay.example.caller;    
    
import android.app.Activity;    
import android.os.Bundle;    
import android.view.View;    
import android.widget.Toast;    
    
public class MainActivity extends Activity {    
    @Override    
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.activity_main);     
    }    
    // Define a method that takes a view component as an argument
    public void myclick(View source)    
    {    
        Toast.makeText(getApplicationContext(), "The label button was clicked.", Toast.LENGTH_SHORT).show(); }}Copy the code

Main.xml layout file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
    xmlns:tools="http://schemas.android.com/tools"    
    android:id="@+id/LinearLayout1"    
    android:layout_width="match_parent"    
    android:layout_height="match_parent"    
    android:orientation="vertical" >    
    <Button     
        android:layout_width="wrap_content"    
        android:layout_height="wrap_content"    
        android:text="Button"    
        android:onClick="myclick"/>    
 </LinearLayout> 
Copy the code

3. Event handling mechanism based on callback

1. What is a method callback?

Written expression:

Answer: it is a means of separating function definition from function, a design idea of decoupling; In Java, callback is implemented through interfaces. As a system architecture, it must have its own operating environment and provide users with interfaces to implement it. Implementation depends on the customer, so you can achieve interface unity, implementation is different, the system through in different states “callback” our implementation class, so as to achieve interface and implementation separation!

Here’s a simple example:

For example, when you come home from school on Friday, you ask your mother if the meal is ready. Then you say to her: Mom, I see Pleasant Goat, when you finish cooking, call me! Analysis: you and mom agreed an interface, you through this interface called mom cooking, when the rice cooked, your mom through this interface to feedback you, “rice cooked”!

2.Android callback event handling mechanism

There are two scenarios for using callback-based event handling in Android:

1) Customize the View

Android provides a number of callback methods for GUI components to handle events. In View, for example, there are several methods

  1. Trigger a screen event on this component: Boolean onTouchEvent(MotionEvent Event);
  2. When pressing a button on this component: Boolean onKeyDown(int keyCode,KeyEvent event);
  3. When releasing a button on a component: Boolean onKeyUp(int keyCode,KeyEvent event);
  4. Boolean onKeyLongPress(int keyCode,KeyEvent event);
  5. Boolean onKeyShortcut(int kryCode,KeyEvent event);
  6. Trigger a trackball event screen event on a component: Boolean OnTrackballEvent(MotionEvent Event);
  7. The focus of the component changes, and unlike the previous six, this method can only be overridden in the View! protected void onFocusChanged(boolean gain Focus,int direction,Rect previously FocusedRect);



Code sample

MyButton.java

public class MyButton extends Button{  
    private static String TAG = "Ha ha";  
    public MyButton(Context context, AttributeSet attrs) {  
        super(context, attrs);  
    }  
  
    // Override the event triggered by the keyboard press
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        super.onKeyDown(keyCode,event);  
        Log.i(TAG, "OnKeyDown method called");  
        return true;  
    }  
  
    // Override the event triggered by the keyboard being pressed
    @Override  
    public boolean onKeyUp(int keyCode, KeyEvent event) {  
        super.onKeyUp(keyCode,event);  
        Log.i(TAG,"OnKeyUp method called");  
        return true;  
    }  
  
    // The component is touched
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        super.onTouchEvent(event);  
        Log.i(TAG,"OnTouchEvent method is called.");  
        return true; }}Copy the code

Layout file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context=".MyActivity">  
    
    <example.jay.com.mybutton.MyButton  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="Button"/> 
Copy the code

Code parsing:

Because we have directly overwritten Button’s three callback methods, we do not need to bind event listeners in Java files to complete the callback when a click event occurs, i.e. the component handles the corresponding event, i.e. the event is handled by the event source (component) itself!

2) Event propagation based on callback:



The order of propagation is listeners – > callback methods for the View component – > callback methods for the Activity

The sequence of events propagated takes precedence over listeners, then to the View component itself, and finally to the Activity; Return false to continue propagation, true to terminate propagation ~!

4. Brief analysis of the message transmission mechanism of Handler

1. First look at the learning roadmap:



2. Then we introduce the Handler class:



3. Look at the flow chart of Handler execution:

UI thread: this is our main thread. The system initializes a Looper object and creates a MessageQueue associated with the UI thread. Handler: Sends and processes messages. In order for this Handler to work properly, there should be a Looper object in the current thread called Message MessageQueue: Message queue, fifO management Message, creating a MessageQueue associated with the Looper object when it is initialized; Looper: Each thread can have only one Looper, manage MessageQueue, and continuously pull messages from it to distribute to the corresponding Handler!

4. Related methods of Handler:

Void handleMessage(Message MSG): The method used to process messages, usually to be overridden! SendEmptyMessage (int What): sends an empty Message sendEmptyMessageDelayed(int what,long delayMillis): sends an empty Message sendMessage(Message) in milliseconds MSG): send the Message immediately sendMessageDelayed(Message MSG): Send the Message in milliseconds. Final Boolean hasMessage(int WHAT): Check whether the Message queue contains the Message whose what attribute is the specified value If the parameter is (int WHAT,Object Object): In addition to determining the what attribute, it is also necessary to determine whether the Object attribute is the message of the specified Object

5. Examples of using this Handler:

1) Handler is written in the main thread

In the main thread, since the system has already initialized a Looper object, we can create a Handler object to send and process information.

If the Handler is written in the child thread, we need to create our own Looper object! The creation process is as follows:

1) The Looper object is created for the current thread by calling looper.prepare () directly, and its constructor creates the corresponding MessageQueue. 2) Create a Handler object and override the handleMessage() method to handle messages from other threads! 3) Call looper.loop () to start Looper

5.TouchListener PK OnTouchEvent + Multi-touch

1. TouchListener based on listener

OnTouchListener:

OnTouch (View V, MotionEvent Event): The following parameters are the components that trigger the touch event in turn. The touch event encapsulates the detailed information of the trigger event, including the event type and trigger time. For example, event.getx (), event.gety () can also be used to determine the action type of the touch, using event.getAction(). Such as: Event. The getAction = = MotionEvent. ACTION_DOWN: ACTION_MOVE: Move the event. GetAction == MotionEvent.ACTION_UP: Unpress the event

2. Callback based onTouchEvent() method

OnTouchEvent is also a touch event, but onTouchEvent is more for custom views. All view classes override this method, and this touch event is callback-based, meaning that if we return false, the event will continue to be propagated outward by the outside container or Activity To deal with! And, of course, Gesture, which we’ll cover in more detail later! OnTouchEvent is similar to onTouchListener, but the processing mechanism is not the same. The former is a callback and the latter is a listener.

3. Multi-touch

Principle of things: the so-called multi-touch is multiple fingers operating on the screen, the most used estimate is the zoom function, such as many image browsers support zoom! The Android system itself can theoretically handle up to 256 finger touches, depending on the phone’s hardware; However, multi-touch phones usually support 2-4 points, but some of them have more! We found that both of these are useful for motionEvents, which represent a touch event; Event.getaction () & motionEvent.action_mask (); event.getAction() & motionEvent.action_mask ();

Motionevent. ACTION_POINTER_DOWN: Triggered when a point on the screen is already held down and another point is pressed. Motionevent.action_pointer_up: Triggered when multiple points on the screen are held down and one of them is released (i.e., not the last point is released).

The simple process would look something like this:

When we touch the screen with one finger — > triggers an ACTION_DOWN event and then another finger touches the screen — > triggers an ACTION_POINTER_DOWN event, and if there are other fingers touching, Continue to trigger one finger off the screen — > trigger ACTION_POINTER_UP, continue to trigger another finger off the screen — > trigger ACTION_UP when the last finger off the screen — > trigger ACTION_UP and throughout the process, The ACTION_MOVE event will be triggered all the time and we can get the location of the different touch points by calling event.getx (int) or event.gety (int) : For example, event.getx (0) gets the x-coordinate of the first touchpoint, and event.getx (1) gets the x-coordinate of the second touchpoint. Alternatively, we can determine how many fingers are currently touching ~ by calling the getPointerCount() method of the MotionEvent object

6. Listen for content changes in the EditText

1. Listen for changes in the EditText

The OnClickListener function is used to handle text changes. The OnClickListener function is used to handle text changes. TextWatcher, we can call the EditText. AddTextChangedListener (mTextWatcher); Set content change listening for EditText!

To recap the TextWatcher class, we need to implement three methods:

public void beforeTextChanged(CharSequence s, int start,int count, int after);   
public void onTextChanged(CharSequence s, int start, int before, int count);
public void afterTextChanged(Editable s);
Copy the code

It will be triggered in the following situations in sequence: 1. Before the content changes; 2. After the content changes

2. Make passwords visible and invisible in EditText

This is also a useful requirement for the user to make the password in the EditText visible or invisible when the user clicks the button

 @Override
            public void onClick(View view) {
                if(flag == true){
                    edit_pawd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    flag = false;
                    btnChange.setText("Password not visible");
                }else{
                    edit_pawd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    flag = true;
                    btnChange.setText("Password visible"); }}});Copy the code

7. Events that respond to system Settings (Configuration class)

Configuration gives us a list of methods

DensityDpi: screen density fontScale: font size factor set by the current user hardKeyboardHidden: determines whether the hard keyboard is visible. There are two options: HARDKEYBOARDHIDDEN_NO,HARDKEYBOARDHIDDEN_YES, 0 and 1 in hexadecimal respectively: gets the current associated keyboard type: returns the value of this property: KEYBOARD_12KEY (small keyboard with only 12 keys), KEYBOARD_NOKEYS, KEYBOARD_QWERTY (normal keyboard) keyboardHidden: This property returns a Boolean value that identifies whether the current keyboard is available. This property determines not only the hardware keyboard of the system, but also the soft keyboard (located on the screen) of the system. Locale: obtains the user’s current language environment. MCC: obtains the country code of mobile signals. MNC: obtains the network code of mobile signals. Ps: determines the current mobile network operator with the country code and network code. NAVIGATION_NONAV, NAVIGATION_DPAD, NAVIGATION_TRACKBALL, NAVIGATION_WHEEL orientation: Gets the orientation of the system screen. Return values for this property: ORIENTATION_LANDSCAPE (landscape screen), ORIENTATION_PORTRAIT (vertical screen) screenHeightDp, screenWidthDp: screen available with height and width, use DP to represent the touchscreen: Gets the touch mode of the system touch screen. Return values of this property: TOUCHSCREEN_NOTOUCH (no touch screen), TOUCHSCREEN_STYLUS (touch pen touch screen), TOUCHSCREEN_FINGER (touch screen for receiving fingers)

8.AsyncTask Asynchronous tasks

1) What is multithreading

Answer: Know these names first: Application, Process, thread, multi-threaded applications (Application) : in order to complete a specific task, a set of instruction set and written in a language (a set of static code) Process (Process) : a running program, system scheduling and resource allocation of a separate unit, the operating system will allocate a memory space for each Process, Thread: a smaller unit of execution than a process, each process may have multiple threads, threads need to be placed in a process to execute! Threads are managed by applications!! The process is scheduled by the system!! The concept of Multithreading: the execution of multiple instructions in parallel, in which CPU time slices are allocated to each thread according to a scheduling algorithm. The execution is actually time-shared, but the switching time is so short that the user feels it is simultaneous.

2) Concepts of synchronous and asynchronous:

  1. Why did Android introduce asynchronous tasks

A: When an Android application starts, it starts a Main Thread, which handles uI-related events. Sometimes we call it a UI thread! In Android apps we have to follow the rules of the single-threaded model: Android UI operations are not thread-safe and they need to be performed in the UI thread! Let’s say we open another Thread in a non-UI Thread, such as new Thread() in the main Thread, and change the VALUES of UI controls directly in it. This throws the following exceptions: android. View. ViewRoot $CalledFromWrongThreadException: Only the original thread that created a View Hierarchy can touch its views. If we put time-consuming operations in the UI thread, If the UI thread does Not respond to the request after 5s, an ANR(Application Not Responding) exception will be raised. android.os.NetworkOnMainThreadException

1. Why AsyncTask? A: We can use the above two methods to complete our asynchronous operations, adding asynchronous operations that require us to write a lot, or tedious, should we new Thread() and use the above method to notify the UI update? Programmers tend to be lazy, so why not use AsyncTask, a lightweight, wrapped asynchronous class? We can do our asynchronous operations with dozens of lines of code and a manageable schedule; Compared to Handler, AsyncTask is much simpler and faster. Of course, it is only suitable for simple asynchronous operations. In addition, the most practical use of AsyncTask is network operations, image loading, data transfer, etc. However, when the company did real projects, we used more third-generation frameworks, such as Volley,OkHttp, Android-Async-HTTP,XUtils and many others. We will choose one or two frameworks for further tutorials. Of course, you can find materials to learn by yourself. But it is necessary to master AsyncTask!

2) Basic structure of AsyncTask :AsyncTask is an abstract class. Generally, we will define a class that inherits AsyncTask and overrides related methods

Arguments to subclass AsyncTask:

Related methods and execution process:

Matters needing attention:

9. Gestures (Gestures)

1. The execution order of gesture interaction in Android

1. Trigger the MotionEvent event when your finger touches the screen! 2. The event is listened on by OnTouchListener, and the MotionEvent object is available in its onTouch() method! 3. Forward the MotionEvent object to OnGestureListener 4 through the GestureDetector. We can use OnGestureListener to get this object, and then get related information, and do related processing!

conclusion

The article is my online combination of various materials and their own learning Android experience, only for the beginning of learning Android children’s shoes reference, but also for their own learning to write. Keep it up!