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 • • • • • • • This unit will be divided into these sections: 1. Introduction 2. Views, layouts, and resources 3. The activity_main.xml file 4. The strings.xml file 5. The R.java class 6. The MainActivity.java file 3 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 would be 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 6 7 • These are some of the topics that will be covered in this unit in brief: • Views in apps • XML and app layout • Graphical components of apps • The relationship between apps and resources • The specification of id’s in apps • Adding functionality to apps 8 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 section is to trace through the contents of MyEchoApp • It 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 in the built Java code) MainActivity.java (the application source code) 19 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 • 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 • The layout of MyFirstApp was based on what is known as RelativeLayout • What the layout contained was known as a TextView 22 23 • 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 • As noted above, MyFirstApp uses a RelativeLayout • It contains a TextView • The TextView contains this: • android:text="@string/hello_world" 28 • • • • The RelativeLayout is a so-called root view The TextView is a so-called child view The idea is straightforward The layout root organizes the child views that it contains 29 • The layout of MyEchoApp is based on the same organizing principles as MyFirstApp, but its 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 30 31 • The screenshot on the following overhead shows the editor view of the activity_main.xml file for MyEchoApp 32 33 • The complete activity_main.xml code for MyEchoApp is shown on the following overhead 34 • • • • • • • • • • • • • • • • • • • • • • • • <?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> 35 The activity_main.xml Code for MyEchoApp Line-by-Line • The following overheads will go through the XML code 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 • It 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 36 • 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 again in the future 37 • 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 38 • 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. --> 39 • 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 40 • xmlns stands for XML name space • For the time being we can just copy and carry this without needing to know the details • • xmlns:android=http://schemas.android.com/apk/res/android xmlns:tools="http://schemas.android.com/tools" 41 • 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" 42 • 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"> 43 • Following the declaration of 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 44 The EditText View • This is the complete code for EditText: • • • • • <EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:hint="@string/text_message" android:id="@+id/edit_message" /> 45 EditText Line-by-Line • This line introduces the first child/view/graphical component that belongs to the LinearLayout, the editable text field • <EditText 46 • 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" 47 • This next line specifies a string resource associated with the text field • android:hint="@string/text_message" /> • @string is the way of designating this • 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 48 • 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 • Referring back to the app screenshot, you can see that the value of this string is “Enter a string” 49 • The activity_main.xml file won’t compile successfully until text_message has been included in the strings.xml file • A line like this one will appear in R.java after a successful compilation of the code with the declaration shown above • public static final int text_message=0x7f040001; 50 • The next line is the most “suggestive” 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 51 • This is the syntax of the line: • It is defining an android id • The use of @ is similar to its use in the line that designated a string resource • @ in general indicates a reference to a resource • The + is necessary in this line because this is the initial definition of the resource • The + is not used for simple string resources, but is needed when declaring resources like id’s for the first time 52 • The critical 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 53 • The process of defining an id is tied up with the R.java class • A line like this one will appear in R.java after a successful compilation of the code with the declaration shown above • public static final int edit_message=0x7f070000; • At a system level, an id is a unique integer identifier (like a hashcode) for a resource 54 • Eventually, we will be writing code in the ActivityMain.java file which implements functionality for the app • When doing so, the edit_message identifier for the EditText view will be referred to in this way: • R.id.edit_message 55 • 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 component’s display characteristics are defined, its string is defined, and its id is defined 56 The Button View • This is the complete code for Button: • • • • • <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/button_echo" android:onClick="sendMessage" /> 57 Line-by-Line • This line introduces the second child/view/graphical component that belongs to the LinearLayout, the button • <Button 58 • 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" 59 • 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 60 • This line is the most “suggestive” 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 • The sendMessage() method is java code which will be implemented in the MainActivity.java file • This will be covered in a future section 61 • 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 62 The TextView • This is the complete code for TextView: • • • • • <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/echo_placeholder" android:id="@+id/echo_message" /> 63 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 64 • 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" 65 • 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.” 66 • This line defines another id, which will ultimately appear in R.java • android:id="@+id/echo_message" /> • This id is critical to the app • In MainActivity.java, this id will be used when accessing the TextView to do output 67 • 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 68 Ending the Layout • This line ends the definition of the LinearLayout • </LinearLayout> 69 A Side Note on Names of Resources and Scope • If you were to go to the Android developer’s Web site, you would find an example app similar to the one being developed here • For the purposes of illustration, XML code similar to the tutorial code is given on the following overhead • Note that the id at the top and the string at the bottom have the same name 70 • • • • • • <EditText android:id="@+id/edit_message" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:hint="@string/edit_message" /> 71 • 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 72 • 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 73 4. The strings.xml File 74 • The screenshot on the following overhead shows the editor view of the strings.xml file for MyEchoApp 75 76 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> 77 • 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 78 • 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 79 5. The R.java Class 80 • The screenshot on the following overhead shows the editor view of the R.java file for MyEchoApp 81 82 • 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 83 • 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 84 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; } 85 • • • • • 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; } 86 • • • • • • • • 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; 87 6. The MainActivity.java File 88 • The screenshot on the following overhead shows the editor view of the MainActivity.java file for MyEchoApp 89 90 Here is the Java Code: • The complete code for MainActivity.java is considered section-by-section beginning on the following overhead 91 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; 92 • 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; 93 The App Class • This is the class of the app as provided by the system • public class MainActivity extends Activity { 94 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); • } 95 • 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; • } 96 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 • If it’s specified in the layout but not provided in implemented in ActivityMain.java, you won’t get a clean compile 97 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 98 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 99 • 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 100 • 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 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 • Activities will be explained in greater detail in a future set of overheads • In the current example we can simply accept that such calls can be made 101 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 102 • EditText editText = (EditText) findViewById(R.id.edit_message); • String message = editText.getText().toString(); • TextView echoText = (TextView) findViewById(R.id.echo_message); • echoText.setText(message); • } • } 103 • The calls to get and set the text string are straightforward • The calls to acquire the reference 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 104 • 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 105 • 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 • We don’t know the type being returned here, but accept the fact that it has to be converted to a String using our friend toString() 106 • 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 107 • 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 108 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. 109 • 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 110 • 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 111 • 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 112 The End 113 • The following slides contain the complete MainActivity.java code done with the explanations as comments rather than as PowerPoint bullets 114 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. */ 115 • • • • • /* 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; 116 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); } 117 • /* 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; • } 118 • /* 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) { 119 • /* */ • • • • • • • • • • /* * * * * * * * * * • • • • • • 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. */ 120 • • /* 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); } } 121