Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Android 4: A Second Project Kirk Scott 1 2 Outline • • • • • • • This unit will be divided into these sections: 4.1 Introduction 4.2 Views, layouts, and resources 4.3 The activity_main.xml file 4.4 The strings.xml file 4.5 The R.java class 4.6 The MainActivity.java file 3 4.1 Introduction • The overall plan of all of the sets of overheads is to gradually grow some examples which illustrate how to do things • It is not practical to cover each relevant topic in depth before applying it • There are too many topics and they are too extensive 4 • Eventually, after covering enough examples, it will become possible to delve into individual topics in some depth • Examples and background information are interspersed throughout the sets of overheads • The background may help give context to previous examples and may provide a starting point for understanding future examples 5 • On the following overhead a screenshot is given of the example that will be pursued in this unit • The goal is to develop an app that allows the user to enter text into a field and press a button to have the text echoed on the screen • In other words, the goal is move one step beyond Hello World to a rock bottom simple echoing program 6 7 • These are some of the topics that will be covered in this unit in brief: • Views in apps (the term View has a specific meaning in Android) • XML and app layout • Graphical components of apps • The relationship between apps and resources • The specification of id’s for various components in apps • Adding functionality to apps 8 4.2 Views, Layouts, and Resources 9 Views and Layouts • The logic of Android app layout has some similarities with the way layouts are accomplished in Java swing • You may be reminded of how components are added to panels, for example, or how focus belongs to focus traversal groups • However, there are major differences in the way things are accomplished in practice 10 • The layout of an Android app can be conceptualized as view groups and views • View groups are overall containers for views or other view groups • The term view refers to specific, individual graphical components like buttons, text fields, etc. • Some of these individual items are known generically as widgets in Android 11 • In concrete terms, one of the most basic differences between Java applications and Android apps is that the layout of an app is stored in a separate .xml file • To a certain extent, this is inconvenient, because as a developer you have to get used to having various things in different places and keeping track of their relationships 12 • In the long run, it is actually a very useful and practical way of managing the code for apps • It’s sort of like taking the MVC pattern to the extreme • The view is maintained completely separately from the model 13 • There are various advantages to this • For example, there are many different kinds of mobile devices, with screens of different sizes and resolutions • Defining layouts separately helps make it possible to support the same app in many different environments 14 Resources • The same kind of logic applies to managing various resources, including things as simple as the strings that an app displays • It may seem clumsy at first to have strings declared in a strings.xml file • But separating strings from the logic of the code also has advantages 15 • For example, not only do apps run on different devices, they may also be internationalized • Keeping strings separate from program logic makes it reasonably easy to substitute strings in one language for strings in another, or make other substitutions as necessary 16 • The purpose of this section was to give some vocabulary—views and layouts • It was also to give a brief preview of the concrete example that will be pursued— MyEchoApp • The organization and presentation of the following sections directly depends on the idea that various parts of an Android app are stored in different files 17 • The overall goal of the following sections is to trace through the contents of MyEchoApp • This is done by examining the contents of the files related to the app one after the other in the order listed on the following overhead 18 • activity_main.xml (layout) • strings.xml (string resources) • R.java (the resources automatically generated when the Java code is built) • MainActivity.java (the application source code) 19 4.3 The activity_main.xml File 20 • The activity_main.xml file contains the formatting for an app • Information concerning this file will be presented in this way: • A. A review of what the file contained for MyFirstApp • B. A presentation of the complete file for MyEchoApp • C. A line-by-line discussion of the contents of the file for MyEchoApp 21 Layout for MyFirstApp • The screenshot on the following overhead shows the Graphical Layout view of the activity_main.xml file for MyFirstApp • This just serves as a reminder of what you saw in a previous unit 22 23 • The layout of MyFirstApp was based on what is known as RelativeLayout • What the layout contained was known as a TextView • These terms show up when you start looking at the XML for the layout • The screenshot on the following overhead shows the editor view of the activity_main.xml file for MyFirstApp 24 25 • The complete activity_main.xml code for MyFirstApp is shown on the following overhead 26 • • • • • • • • • • • • <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi d" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> </RelativeLayout> 27 • Most of the details of importance will be discussed when going through the activity_main.xml file for MyEchoApp • That will be done immediately after this summary review of the layout for MyFirstApp 28 • As noted above, MyFirstApp uses a RelativeLayout • The RelativeLayout is a so-called root view • It contains a TextView • The TextView is a so-called child view • The idea is straightforward • The layout root organizes the child views that it contains 29 • The TextView contains this: • android:text="@string/hello_world" • This is a reference to the resource defined in strings.xml • This is the actual text that’s displayed in the TextView 30 Layout for MyEchoApp • The layout of MyEchoApp is based on the same organizing principles as MyFirstApp, but the layout is different and it contains more views • The screenshot on the following overhead shows the Graphical Layout view of the activity_main.xml file for MyEchoApp 31 32 • The screenshot on the following overhead shows the editor view of the activity_main.xml file for MyEchoApp 33 34 • The complete activity_main.xml code for MyEchoApp is shown on the following overhead 35 • • • • • • • • • • • • • • • • • • • • • • • • <?xml version="1.0" encoding="utf-8"?> <!-- This is the activity_main.xml file for My Echo App. --> <LinearLayout 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" android:orientation="vertical" > <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:hint="@string/text_message" android:id="@+id/edit_message" /> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/button_echo" android:onClick="sendMessage" /> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/echo_placeholder" android:id="@+id/echo_message" /> </LinearLayout> 36 The activity_main.xml Code for MyEchoApp Line-by-Line • The following overheads will go through the XML code for MyEchoApp line-by-line • The goal is not to cover XML in detail • The goal is to get an initial idea of the connection between the XML and the appearance of the application • The goal is also to get an idea of how the connection is made between the XML components and what will be the functionality of the application 37 • It is worth noting again that the Graphical Layout view has a palette you can use to drag and drop components into a layout • The first items in the palette are Form Widgets, Text Fields, Layouts • You could create a layout by dragging and dropping • You were invited to try this at the end of the last set of overheads • It will come up again in the future 38 • The point now is to look at the XML • It’s helpful to have some familiarity with the XML that is generated in order to later become an intelligent user of the tools in the palette • Generating the graphical components is pretty mechanical • The important part will be the connection between them and the functionality of the application 39 Line-By-Line Starts Now • The first line of activity_main.xml gives the version • <?xml version="1.0" encoding="utf-8"?> • The second line illustrates the form of a comment in XML • <!-- This is the activity_main.xml file for My Echo App. --> 40 • The third line declares the kind of layout that is being created for the app • The LinearLayout is sort of like the FlowLayout in swing • Another parameter will be given lower down which clarifies how LinearLayout works • <LinearLayout 41 • For the time being we can just copy and carry the following lines without needing to know the details • It is worth noting that in these lines, xmlns stands for XML name space • • xmlns:android=http://schemas.android.com/apk/res/android xmlns:tools="http://schemas.android.com/tools" 42 • The LinearLayout is in effect a child of the device it’s running on • The following two lines specify that the LinearLayout should take up the full space of the display of its parent • android:layout_width="match_parent" • android:layout_height="match_parent" 43 • The next line sets a parameter relevant to how the LinearLayout is displayed • LinearLayout presents views (components) in order as they’re added • The orientation of the added items can be horizontal or vertical • android:orientation=“vertical"> 44 • Following the declarations related to the overall layout come the three child views that it contains • They are: • EditText—this will allow data input • Button—this will have an action • TextView—this will show the output 45 The EditText View • This is the complete code for EditText, the first child view in the LinearLayout of the app: • • • • • <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:hint="@string/text_message" android:id="@+id/edit_message" /> 46 EditText Line-by-Line • This line introduces the first child/view/graphical component that belongs to the LinearLayout, the editable text field • <EditText 47 • These lines state that the size of the text field will be defined by the height and width of the string that it contains • android:layout_height="wrap_content" • android:layout_width="wrap_content" 48 • This next line specifies a string resource associated with the text field • android:hint="@string/text_message" /> • android:hint tells you the role that this string will play in the app • The hint is the thing that is displayed in the text field by default 49 • android:hint="@string/text_message" /> • Quotation marks and @string are the syntax for designating a string resource • text_message is the symbolic name of the string • The actual definition of the string is done in the strings.xml file, here: /res/values/strings.xml • Referring back to the app screenshot, you can see that the value of this string is “Enter a string” 50 • The activity_main.xml file won’t compile successfully until text_message has been included in the strings.xml file • After a successful compilation of the code with the string declaration shown above a line like this one will appear in R.java • public static final int text_message=0x7f040001; 51 • The next line is the most significant of the lines of code in EditText • android:id="@+id/edit_message" • This line of code assigns an id to the EditText view that is being created • The view can be referred to by this id in the Java code for the app 52 • This is the syntax of the line: • It is defining an android id • The use of @ in general indicates a reference to a resource • The + is the syntax that makes it possible to assign an id to something at the same time it is initially being declared and defined • In the previous line, + wasn’t necessary because we were referring to a string that had already been defined and given a name in strings.xml 53 • The point is this: • You are creating a handle which can be used later on in MainActivity.java code to refer to this view, the EditText element of the layout • Layouts contain views and can refer to strings by id • Code can refer to views by id • Using references, code ultimately displays layouts containing strings 54 • After successful compilation of a project containing this line: • android:id="@+id/edit_message" • A line like this one will appear in R.java • public static final int edit_message=0x7f070000; 55 • At a system level, an id is a unique integer identifier (like a hashcode) for a resource • The id’s, as they appear in R, are the handles for resources which can be referred to in ActivityMain.java, the Java source file for the app • When using this handle, the edit_message identifier for the EditText view will be referred to in this way: • R.id.edit_message 56 • In summary, this is what we just looked at, lineby-line • • • • • <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:hint="@string/text_message" android:id="@+id/edit_message" /> • The EditText component’s display characteristics are defined, its string is defined, and its id is defined 57 The Button View • This is the complete code for Button, the second child view in the LinearLayout of the app: • • • • • <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/button_echo" android:onClick="sendMessage" /> 58 Line-by-Line • This line introduces the second child/view/graphical component that belongs to the LinearLayout, the button • <Button 59 • The button will contain a label • These lines state that the size of the button will be defined by the height and width of that label • android:layout_height="wrap_content" • android:layout_width="wrap_content" 60 • This line specifies a string resource associated with the button • android:text="@string/button_echo" /> • @string is the way of designating this • button_echo is the symbolic name of the string • The actual definition of the string is done in the strings.xml file, here: /res/values/strings.xml • The activity_main.xml file won’t compile successfully until button_echo has been included in the strings.xml file 61 • This line is the most significant of the lines of code in Button • android:onClick="sendMessage" /> • This line of code gives the name of the method, sendMessage(), that will be called when the app is running and the button is clicked 62 • The sendMessage() method is java code which will be implemented in the MainActivity.java file • The name and purpose (event handling) of the method are predetermined 63 • In summary, this is what we just looked at line-by-line • • • • • <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/button_echo" android:onClick="sendMessage" /> • The component’s display characteristics are defined, its string is defined, and it is associated with an action 64 The TextView • This is the complete code for TextView, the third child view in the LinearLayout of the app: • • • • • <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/echo_placeholder" android:id="@+id/echo_message" /> 65 Line-by-Line • This line introduces the third child/view/graphical component that belongs to the LinearLayout, the text view • A TextView simply displays a string • <TextView 66 • These lines state that the size of the text view will be defined by the height and width of the string that it contains • android:layout_height="wrap_content" • android:layout_width="wrap_content" 67 • This line specifies a string resource associated with the text field • android:text="@string/echo_placeholde r" • The resource, named echo_placeholder, would have to be defined in strings.xml • Looking at the screenshot of the app, you see that this string is defined to have this value: “Your input will be echoed here.” 68 • This line defines another id of this text view • android:id="@+id/echo_message" /> • This works the same way as explained for the edit text component • It will result in this id appearing in R: • R.id.echo_message 69 • The edit text and text view components are the input and output parts of the echoing • The sendMessage() method is the functionality • In the code for sendMessage() the id’s of the input and output components will be referred to in order to make the app work 70 • In summary, this is what we just looked at line-byline • • • • • <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/echo_placeholder" android:id="@+id/echo_message" /> • The component’s display characteristics are defined, its string is defined, and its id is defined 71 Ending the Layout • This line ends the definition of the LinearLayout • </LinearLayout> 72 A Side Note on Names of Resources and Scope • XML code similar to the code we just looked at is given on the following overhead • Note that the id at the top and the string at the bottom have the same name • You may run across example code written by other programmers with this characteristic 73 • • • • • • <EditText android:id="@+id/edit_message" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:hint="@string/edit_message" /> 74 • It is possible for two things to have the same name because id’s and strings are two distinct kinds of things • In the R.java (resource) file, the reference identifiers for id’s and strings are in different sets of braces, so they can be distinguished 75 • Even though it’s possible to have different things with the same name, I think it’s a bad idea that will lead to confusion • I will give everything different names even if they are of different types 76 4.4 The strings.xml File 77 • The screenshot on the following overhead shows the editor view of the strings.xml file for MyEchoApp 78 79 Here is the XML Code: • • • • • • • • • <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">My Echo App</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">MainActivity</string> <string name="text_message">Enter a string</string> <string name="button_echo">Echo</string> <string name="echo_placeholder">Your input will be echoed here.</string> </resources> 80 • It is not necessary to examine strings.xml line by line on separate overheads • It is apparent that the first 3 lines in the file consist of overall app related strings which are supplied by the system 81 • The last 3 lines in strings.xml are the strings associated with the views in the app • The XML syntax for naming the string and giving it a value is apparent • As noted earlier, you won’t get a clean compilation unless the strings mentioned in activity_main.xml are defined in this way in strings.xml 82 4.5 The R.java Class 83 • The screenshot on the following overhead shows the editor view of the R.java file for MyEchoApp 84 85 • The code from the top of the R.java file is given on the following overheads • All resources have automatically generated identifiers in R.java as a result of successful compilation 86 • These resources can be strings from strings.xml, id’s from activity_main.xml, or other resources • The app’s Java code refers to its resources through the R.java file 87 Here is the Code for R.java • • • • • • /* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ • package com.example.myechoapp; • • • • • • • public final class R { public static final class attr { } public static final class drawable { public static final int ic_launcher=0x7f020000; } 88 • • • • • public static public public public } final class id { static final int echo_message=0x7f070001; static final int edit_message=0x7f070000; static final int menu_settings=0x7f070002; • • • public static final class layout { public static final int activity_main=0x7f030000; } • • • public static final class menu { public static final int activity_main=0x7f060000; } 89 • • • • • • • • public static public public public public public public } final class string { static final int app_name=0x7f040000; static final int button_echo=0x7f040002; static final int echo_placeholder=0x7f040005; static final int menu_settings=0x7f040003; static final int text_message=0x7f040001; static final int title_activity_main=0x7f040004; 90 4.6 The MainActivity.java File 91 • The screenshot on the following overhead shows the editor view of the MainActivity.java file for MyEchoApp 92 93 Here is the Java Code: • The complete code for MainActivity.java is considered section-by-section beginning on the following overhead 94 Package and Imports • If you use the development environment it will automatically put your app into a package • package com.example.myechoapp; • Here are the general imports for the app • import android.os.Bundle; • import android.app.Activity; • import android.view.Menu; 95 • You need to import the view classes in order to work with them in your code • These are the Android classes that correspond to the views in the layout in activity_main.xml • import android.view.View; • import android.widget.EditText; • import android.widget.TextView; 96 The App Class • This is the class of the app as provided by the system • public class MainActivity extends Activity { 97 The Standard Provided Methods • The onCreate() method is the moral equivalent of a main() method • It’s provided by the system if you use the development environment • @Override • protected void onCreate(Bundle savedInstanceState) { • super.onCreate(savedInstanceState); • setContentView(R.layout.activity_main); • } 98 • The onCreateOptionsMenu() method is also system provided • Until we develop an app with a menu, we don’t have to worry about it • @Override • public boolean onCreateOptionsMenu(Menu menu) { • // Inflate the menu; this adds items to the action bar if it is present. • getMenuInflater().inflate(R.menu.activity_main, menu); • return true; • } 99 The sendMessage() Method • The sendMessage() method is needed in the Java code for the app • This method is specified in activity_main.xml as the method to be called when the button in the layout which belongs to the app is clicked 100 • If it’s specified in the layout but not implemented in ActivityMain.java, you won’t get a clean compile • In other words, you don’t inherit this from Activity • Not all apps have buttons, so not all apps have a sendMessage() method • You have to supply one if your app does have a button 101 The Signature and Explicit Parameter of the sendMessage() Method • Here is the signature of the method: • public void sendMessage(View view) { • Remember that in layout terms, the button is a view • The view that comes in as a parameter to the method when the button is clicked is a reference to the button • In the code for the method you don’t have to acquire a reference to the button separately 102 A Preliminary Description of the Body and the Implicit Parameter of the sendMessage() Method • The body of the sendMessage() method will come next • Obviously it’s important because this is where the echoing logic of the app is implemented • It’s also important because in this code you see how you can acquire references to the views in the layout belonging to the app 103 • The reference to the button comes in as the explicit parameter • You have to call methods in order to access the input, EditText, and output, TextView, views • You will see that the method calls are floating in space • These calls to acquire references to the views are made on the implicit parameter 104 • Speaking concisely, the implicit parameter is the MainActivity that is currently being executed • This is an important topic • In the example in the next set of overheads, it will be necessary to pass the MainActivity around as an explicit parameter so that calls such as these can be made on it elsewhere 105 • Activities will be explained in greater detail in a future set of overheads • In the current example we can simply accept that calls can be made on activities in order to acquire references to the views that belong to them 106 The Body of the sendMessage() Method • The process of echoing in the app consists of 4 steps: • 1. Acquire a reference to the input, EditText, view • 2. Acquire the string from the input view • 3. Acquire a reference to the output, TextView, view • 4. Put the string into that view • The complete code is shown on the following overhead • After that, the code is examined line-by-line 107 • EditText editText = (EditText) findViewById(R.id.edit_message); • String message = editText.getText().toString(); • TextView echoText = (TextView) findViewById(R.id.echo_message); • echoText.setText(message); • } • } 108 • The calls to get and set the text string are straightforward • The calls to acquire the references have two critical elements: • 1. You specify the view you want a handle on by sending its R.java id as a parameter. • 2. You have to cast the return value to the specific kind of view you were expecting back 109 • Looking back at the contents of R and the way the code works here, you can kind of gather what’s going on: • When you cast, it’s more or less like recovering a subclass reference from a superclass reference • The superclass would literally be View, but in R, there is a separate id concept—where the id’s are hex values—hashcodes for actual objects of a given class(?) 110 • In any case, in practice this is how you get a handle on the input, EditText, view • EditText editText = (EditText) findViewById(R.id.edit_message); • Remember, edit_message originated in layout.xml • It exists in R.java as a result of compilation • It belongs to the app because these files are all parts of the same project 111 • This is how you acquire the text from the field • String message = editText.getText().toString(); • In some contexts, a getText() method might return a String, but here we have to cast 112 • We don’t know the type being returned here, but looking at the way things are structured, we can again speculate • Maybe getText() returns the R id of the reference to the string in strings.xml… • And for that kind of id, toString() has been implemented to return the string value… 113 • This is how you get a handle on the output text view • TextView echoText = (TextView) findViewById(R.id.echo_message); • This is analogous to acquiring the handle for the input view 114 • This is how you assign a string to the output text view • • • } echoText.setText(message); } • It’s a little odd that getText() from an EditText view apparently doesn’t return a String, but setText() on a TextView expects a String, but so be it 115 Summary and Mission • After 100+ overheads, your head can spin a little • What was this all about? • In summary, it covered everything you needed to know, every aspect of any file that you as a programmer need to touch, in order to create an echoing application. 116 • From a Java programmer’s point of view, the sendMessage() method is where the real work happens • However, it doesn’t really take that much work there at all • This is the result of offloading layout, resources, etc. to other locations 117 • The challenge is keeping track of all of the different files in the project, what has to go into them, and their relationships to each other • As seen, the final thing you have to be aware of in the code for MainActivity.java is how to get a handle on the views that belong to the app 118 • What is your mission? • There is no separate mission for this set of overheads • The next set of overheads expands on the topics introduced here and ends with the first assignment that you will need to do and turn in 119 The End 120 • The following slides contain the complete MainActivity.java code done with the explanations as comments rather than as PowerPoint bullets • It gives the same information in a more compact form • The descriptions are less complete, but you can essentially take everything in at once in a few short glances 121 Package and Imports • • /* If you use the development environment it will * automatically put your app into a package. */ • package com.example.myechoapp; • /* • • • import android.os.Bundle; import android.app.Activity; import android.view.Menu; Here are the general imports for the app. */ 122 • • • • • /* You need to import the view classes in order to work with * them in your code. These are the Android classes that * correspond to the views in the layout in * activity_main.xml. */ • • • import android.view.View; import android.widget.EditText; import android.widget.TextView; 123 The App Class and the Standard Provided Methods • • /* This is the class of the app as provided by * system. */ • public class MainActivity extends Activity { • • • • /* This method is the moral equivalent * of a main() method. It’s provided * by the system if you use the development * environment. */ • • • • • @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } 124 • /* This method is also system • * provided. Until we develop an app • * with a menu, we don’t have to worry • * about it. */ • @Override • public boolean onCreateOptionsMenu(Menu menu) { • // Inflate the menu; this adds items to the action bar if it is present. • getMenuInflater().inflate(R.menu.activity_mai n, menu); • return true; • } 125 • /* The sendMessage() method is called when the • * button in the layout which belongs to the app • * is clicked */ • /* This is very important: Remember that in • * layout terms, the button is a view. • * The view that comes in as a parameter to • * the method when the button is clicked • * is a reference to the button. */ • public void sendMessage(View view) { 126 • /* */ • • • • • • • • • • /* * * * * * * * * * • • • • • • The body of the sendMessage() method will come next. This is very important: In order to get handles on the other views in the layout of the app so that you can work with them in the app code, you have to call methods to acquire them. You will see that the calls are floating in space—they’re on the implicit parameter. At this point we don’t really know what the implicit parameter is. More explanations will come later. For the time being, accept that the calls can be made. Notice these two critical elements of the calls: * 1. You specify the view you want a handle on by * sending its R.java id as a parameter. * 2. You have to cast the return value to the specific * kind of view you were expecting back. */ 127 • • /* The following code accomplishes echoing by taking * in input and transferring it to output. • /* */ • EditText editText = (EditText) findViewById(R.id.edit_message); • • /* This is how you acquire the text from the field. String message = editText.getText().toString(); • /* This is how you get a handle on the output text view. • TextView echoText = (TextView) findViewById(R.id.echo_message); • /* */ • • • This is how you get a handle on the input edit text view. */ */ This is how you assign a string to the output text view. echoText.setText(message); } } 128