Science Quiz Android Application - Part 2
As we know that the default layout for an Activity consists of a
RelativeLayout holding a
TextView with text Hello World!, hence we will have to change ti, as we are building a Science Quiz app. For our App, we will setup the screen like shown in the below snapshot, and for that, we will require:
Remove the existing XML code from the file
activity_science.xml and write the following code in the layout file.
<?xml version="1.0" encoding="utf-8"?>
You will notice 3 strings marked in red, do not worry about them right now, we will come back to that later.
On changing the layout xml file you will notice that the preview has also changed. Each of the XML elements, namely
Button represents a widget and their XML attributes defines how the widget will be configured, like what text to show in the
TextView, is configured by
android:text attribute. Same is the case for text to be displayed on
Hierarchical Layout of Widgets and Attributes
Let's try to understand the layout. As we can see from the above XML,
LinearLayout is the root element, which has height and width equal to the device screen defined by the attributes
android:layout_height="match_parent". Also it defines the orientation for its child elements to be Vertical.
the two child widgets of the root
LinearLayout are a
TextView and another
LinearLayout has further two childs,
Button which are horizontally placed inside the
LinearLayout as it is defined as an attribute
android:orientation in the child
We have also specified
android:id attribute for the two
Button widgets. This is done, so that we can reference and use the buttons in our Activity class, we will see how to do that in the next tutorial.
Creating string resource
In every Android project one
strings.xml file is already added. In the Project tool window, in your project, find app/res/values if you have selected the Android style structure, and app/src/main/res/values if your Project tool window is in Project view. If you do not know how to switch between Android package structure and Project, follow the below image.
It is a standar practice to define String values separately in the
strings.xml file. The format in which you can specify any string value is the following:
Once a string is declared in the
strings.xml file, it can be directly used in the layout xml file using
@string/STRING_NAME. Now, we have to create three string references in our
strings.xml file, for question_text, true_button and false_button like mentioned below:
Graphite is used in making Pencils.
As you create these 3 strings in the
strings.xml you will see that all the errors in your
layout_science.xml file will be resolved.
If we want we can also have our own separate strings xml file with any name, but it should be located in res/values/ directory.