- What does the Android R class do?
Answer:
It manages the resources in an Android app, for example: ids defined in the
layout file, colors in the
colors.xml file and strings in the strings.xml file. You can
use the id to create a Java object like this:
TextView tv = findViewById(R.id.txt_temp);
- Show how display a string dynamically from the strings.xml resource file.
Answer:
TextView tv = findViewById(R.id.txt_name);
tv.setText(getString(R.string.first_name));
- Show how to change a color dynamically from the
colors.xml resource file. Answer:
LinearLayout layout = findViewById(R.id.main);
layout.setBackgroundColor(getColor(R.color.purple));
// or
layout.setBackgroundColor(0xFFFF00FF);
- How do you change the int value n to
the String value s? Answer:
String s = String.valueOf(n);
// or
String s = n + "";
// or
String s = String.format(n, "%d");
- Change this TempDesc class so that it
has the instance variable temperature, the getter
getTemperature,
the setter setTemperature, and the method getDescriptor,
Also include a parameterized
constructor that initializes the instance variable. Use this UML diagram:
+--------------------------------+
| TempDesc |
+--------------------------------+
| - temperature : double |
+--------------------------------+
| + TempDesc(temp: double) |
| + getTemperature( ) : double |
| + setTemperature(temp : double)|
| + getDescriptor( ) : String |
+--------------------------------+
Test your TempDesc class like this:
double[ ] temps = {-13.0, 27.0, 52.0, 68.0, 87.0, 103.0};
TempDesc tempObj = new TempDesc(0);
String output = "";
for(double temp : temps) {
tempObj.setTemperature(temp);
output += tempObj.getDescriptor( ) + "\n";
}
// Display the output variable contents
// in a TextView widget:
tv.setText(output);
Then display the
output in a TextView widget in an Android app.
Answer: activity_main.xml
MainActivity.java
TempDescriptor.java
- Translate this Java function to Kotlin:
public static String makeGreeting(String name) {
return "Hello, " + name + ", how are you?
}
Then test it by placing these lines at the end of the onCreate method in an app
with language set to Kotlin:
Log.i("001", makeGreeting("Larry"))
View the output in the Logcat window. Answer:
// The Kotlin translation of the makeGreeting function:
fun makeGreeting(name: String) : String {
return "Hello, $name, how are you?"
}
To pull up the Logcat Window, click the corresponding icon on the left of the
Android Studio editor. (The Logcat icon looks like a cat face.) Replace
package:mine by
tag:001 and
clear the Logcat window by right clicking and selecting Clear Logcat.