This is the fifth session of the first part of the Android Development (Introduction) course, Layout and Interaction, taught by Katherine Kuan and Kunal Chawla. The main content is the definition and call of method, the definition of object and the call of method. There are a lot of knowledge points in this lesson. If there are confusing and difficult points, please refer to the Android vocabulary. I hope you can read it patiently and welcome your criticism.

Key words: Method, Android Resouces (AAPT→R Class), onCreate, Object-oriented Programming, Java Class and its inheritance, Java Object, findViewById, Casting Object, Setter&Getter, Log

Method definition and call

  1. Like a variable, method is defined first and then called. Methods are defined for code that can be reused to make the program modular, just like building a car, so that people can use it. You can simplify code when calling method, just like driving a car without having to understand how the car works.

  2. Similar to making a cake, method usually has input and output, flour and sugar → input, recipe → Method code, cake → output.

  3. When the program reaches the method call, it jumps to the method definition, executes the method code from top to bottom, and returns to the method call. In Android Studio, click the method name at the method invocation point and right-click on Go To→Declaration (CMD +B). The interface will jump To the method definition and you can see the source code of the Android framework layer step by step.

  4. Oracle defines method signatures by searching “Define Java Method” on Google. There are strict formatting conventions for defining methods:

Java access modifier returns the name of the data type method (input parameter 1 data type input parameter 1 variable name, input parameter 2 Data type input parameter 2 variable name,...) {...returnThe return value. }Copy the code

(1) The Java Access Modifier commonly used includes private and public. Private refers to method, which can be invoked only within the Activity, and public can be used for all activities.

The output value of method is called the Return value. The Data Type of the returned value of method is defined here, such as int and String. Void if no value is returned.

The method Name can be found in the Oracle documentation above. The method Name starts with a verb, and if it is a single word, it is all lowercase. Use small hump nomenclature for multiple words.

(4) Input parameter format:

Data type variable nameCopy the code

Allow no input or multiple inputs. The usual case for no input is to use global variables within method. Input parameters are contained in parentheses. Multiple input parameters are separated by commas and cannot be exchanged in the same order.

(5) Method code is enclosed in curly braces, and the last line of code outputs a return value. Any code after this value is not executed.

(6) Format of output return value:

Return Return value;Copy the code
  • Return: Java keywords, Google search “Java keywords” to find Oracle documentation. Int, new, private, public, void, this, etc. are Java keywords and cannot be used for Identifiers such as variable names and method names.
  • The return value:One at most, note that it matches the return value data type. Void if there is no return value (void), i.ereturn;, but this line of code is usually deleted.
  • The semicolon ends.
  1. Here is an example of code that defines method.
/**
* Create summary of the order.
*
* @param price of the order
* @return text summary
*/
private String createOrderSummary(int price) {
    return "Name:Kaptain Kunal" +
           "\nQuantity:" + quantity +
           "\nTotal: $" + price +
           "\nThank you!";
}
Copy the code

(1) Input parameter annotation format:

@param Enter the parameter variable name descriptionCopy the code

(2) Format of output parameter annotation:

@return DescriptionCopy the code

There is no need to specify an output parameter here because method has at most one return value.

  1. Here is an example of code that calls method.
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
    int price = calculatePrice();
    displayMessage(createOrderSummary(price));
}
Copy the code

(1) Call createOrderSummary and input variable price (Arguments); Accordingly, the Input Parameters declared at the method definition are called Input Parameters. The concept of parameter passing can be found in the Oracle documentation by googling “Java Method Parameter”. (2) Method can be called in the operation, and the value involved in the operation is the return value of method; Further, passing an operation as an argument rather than declaring a new variable makes the code cleaner. Such as

createOrderSummary(calculatePrice() + 3);
Copy the code

Object-oriented programming

  1. Android App is mainly divided into resource files (including images, audio and video, XML layout files, etc.) and Java code. This classification enables the App to load different resources for different devices without modifying Java code.

  2. Each resource file has an ID, and AAPT generates R class (R.Java) to include these ids, making the resource available through calls. (1) Call format in Java: r. Resource type. Resource name (2) Call in XML format: @ Resource type/resource name

  • Resource types: Drawable, string, Layout, color, Dimen, style, etc.
  • Resource name: the name of the resource defined by the developer.

Examples in Java files: Photo, r.tring. Hello, R.layout.activity_main, R.D.rice_text_view, R.color.red. (2) Examples in XML files: @drawable/photo, @string/hello, @layout/activity_main, @id/price_text_view, @color/red, @dimen/viewgroups_padding, @style/MainActivityText.

  1. OnCreate Method is executed first after App startup, wheresetContentView(R.layout.activity_main);The Layout resource file will be read (enter the Layout ID into the method, which can specify the Layout displayed first after App initialization); You then start parsing the (Inflate) Java object, which forms a multi-level view collection of your App. Finally, you interact with objects, which is Object Oriented Programming.

Object definition and method call

  1. Java objects can be easily understood as the integration of multiple variables. For example, TextView is an object that has a variable like state and many fields like int font size and String text.

  2. Class (TextView.java) defines the object declaration and method as the class (textView.java), that is, the rules that define the TextView, like the floor plan of a commercial house. (1) Class defines a number of fields, that is, global variables to hold the attributes of the object, the name begins with M (member variable). (2) The class defines a number of methods to manipulate fields, which Are called by Android.

Install Chrome plugin Android SDK Search can add (View Source) link on the right side of the Android document title, you can click to open the corresponding Android source code. Developers can use objects without knowing about classes.

  1. A defined Object, also known as an Object Instance, is a concrete realization of an Object, just like building an actual house from the floor plan of a commercial house.

Defining objects has strict formatting conventions:

Object datatype variable name = initial value;Copy the code

(1) Object data type: class name, such as TextView. Object data types are customizable. (2) Variable name: Defines the name of the object, following the variable naming rules, such as textView. (3) Initial value: two ways: constructor (common) and factory method.

  • Constructor:

    New object data type (input parameter); new TextView(content);Copy the code

The input context in parentheses is used to get resources and the runtime environment. Input parameters can be found in the class source file.

  • Factory Methods:

    Object data type. Factory Method name (input parameter);Copy the code

The factory Method name and corresponding input parameters can be found in the Android documentation. Such as

Toast toastMessage = Toast.makeText(content, "Hi", duration);
Copy the code

Use Google to search for new objects. For TextView, ImageView, Button and other objects, when XML appears, they are equivalent to creating the corresponding object in Java, so they can be directly called by method such as findViewById without writing new statements.

  1. Call the method of the object:

    Method name (input parameter);Copy the code

(1) Object Variable Name: note that it is not an Object data type.

  • Called within class: as in

    Enclosing setText (" Hello ");Copy the code

This refers to the current Activity and can be omitted. Private variables and methods of class can be read.

  • Call out of class: as

    TextView. SetText (" Hello ");Copy the code

TextView is the name of the object variable. Only class public variables and methods can be read.

(2) Method Name: indicates the method of the corresponding object data type. (3) Input Arguments: Note the order and data type.

Other concepts

  1. Class inheritance behavior
public class MainActivity extends AppCompatActivity {
Copy the code

AppCompatActivity (ActionBarActivity in older versions) is a component of the Android Support Library that allows older devices to use a new UI. Here, MainActivity is used as an extension to AppCompatActivity, even if MainActivity can use all of AppCompatActivity’s declarations and methods. SetContentView and findViewById.

A MainActivity that chooses not to inherit an AppCompatActivity method can override it via the @Override flag, but can still inherit other methods. For example, the following onCreate function sets the Layout displayed after App initialization using the inherited setContentView method via Override.

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);
}
Copy the code

From the point of view of class Inheritance, appactivity is a parent class (Superclass) and MainActivity is a child class (Subclass). For example, if TextView, ImageView and Button have the same attributes, then View is the parent class (view.java) and TextView is the child class (TextView.java). They are connected by inheritance. This structure illustrates the hierarchy of Android.

  1. Casting Objects

Java connects resources through ids and stores these objects as member variables of class. When findViewById returns a subclass of View, it needs Casting Objects, a good use of Google to search and develop documents, and familiarity with the return value types and Java classes for different methods. The type of the conversion needs to conform to the data type.

TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view);
Copy the code

(1) (TextView) Convert the View class returned by findViewById to TextView, consistent with the data type on the left. (2) Google search “TextView Android” can find textView Android document, using the browser can search for different method return value types. (3) When using only the method of the parent class, there is no need to convert it to the child class.

As of API 26, the return data type of findViewById has been changed fromViewUpdated to<T extends View>(T stands for “Type,” which belongs to Java Generic types, and will be covered later in this course), so ifcompileSdkAbove API 26, findViewById no longer needs to be cast.

  1. Setter & Getter
orderSummaryTextView.setText("" + message);
Copy the code

Examples are setText and setImageResource. These are called setter methods because they are responsible for modifying or manipulating a value of the view (such as the text or image that the view stores). By convention, they begin with “set”. There is another class of methods, called getter methods, whose sole purpose is to “get” a value from a view, such as the current text of the view. By convention, they start with “get”.

Android Studio logs

Log.i("EnterpriseActivity.java"."Captain's Log, Stardate 43125.8. We have entered a spectacular binary star system in the Kavis Alpha sector on a most critical mission of astrophysical research.");
Copy the code

The first parameter is the name of the class from which the logging statement comes. The second parameter is the text you want to display. Log.i() is used here, for “information” level logs. Other level options are as follows:

  • Error: log.e (String, String)
  • Warning: log.w (String, String)
  • Log. I (String, String)
  • Debug: log.d (String, String)
  • Log.v(String, String)

They correspond to different log levels and can be viewed by category during application running.