What The Weird Word! -Android App

What The Weird Word app overview
It has a Single-Activity displaying:
- A text label ‘What the Weird Word!’
- A button ‘Show the Next Weird Word’
- Two text fields across the middle displaying the weird word and its meaning
Let us start by changing the layout file.
To do this, open the file activity_main.xml from app > res > layout if it is not open already.
Then switch to the text version of the code to open the code editor and replace the code in activity_main.xml with the following code.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background" tools:context=".MainActivity"> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" android:padding="16dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:id="@+id/wordLable" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center" android:text="textview"/> </LinearLayout> </androidx.constraintlayout.widget.ConstraintLayout>
You just changed the code Android Studio generated so that it uses a <LinearLayout>.
This is used to display GUI components next to each other, either vertically or horizontally.
- If it is vertical, they are displayed in a single column, and if it is horizontal, they are displayed in a single row.
android:background=”@drawable/background sets a background image to the layout (Please remember to store the PNG image in the “drawable” folder as per your preference.).
android:gravity specifies how an object should position its content on both X and Y-axis.
Any change made to a layout’s XML is reflected in the Android Studio’s design editor, which can be visualized by clicking the Design tab.
- Update the Text view in the code with the following properties.
<TextView android:id="@+id/wordLable" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center" android:text="What The Weird word!" android:textAllCaps="true" android:textSize="30sp" android:textColor="@color/white" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
- Add a new Text view that would display a new weird word with the following properties.
<TextView android:id="@+id/wordName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:gravity="center" android:textColor="@color/white" android:text="Word Name" android:textAllCaps="true" android:textSize="36sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
Note: Switch between the design tab and the text tab to visualize your code in the layout editor.
- Add a third text view to display the meaning of the weird word with the following properties.
<TextView android:id="@+id/wordMeaning" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center" android:text="Word Meaning" android:textColor="@color/white" android:textAllCaps="true" android:textSize="27sp" android:textStyle="italic" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
Adding a Button
Next, let us add a button to the layout using the design editor.
Find the button component in the palette, click and drag it into the design editor so that it is positioned at the bottom, as shown in the image.
Dragging GUI components to the layout is a convenient way of designing and updating the layout.
When you switch to the code editor, you will be able to see that adding the button through the design editor has added some lines of code to the XML file.
Update the button with the following properties.
<Button android:id="@+id/nextWord" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="84dp" android:text="Next Weird Word" android:textSize="24sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.413" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout" />
As a first step, we have designed the layout of the application. Let us see how the layout has turned out by running it on an emulator.While waiting for the application to load on the emulator,
Hardcoding
So far, we have hardcoded the text we want to appear in our text views and buttons using the android:text property:
android:text=”Hello World!”
While this is fine when you are just learning, hardcoding text is NOT the best approach.
But why?
Hardcoding makes localization hard
Suppose you have created an app that is a huge success on your local Google Play Store.
- You now want to make it available internationally in different languages.
- But you have hardcoded the text in your layout files!
Making the app international would be extremely difficult and would require extensive reprogramming.
Hardcoding makes making global changes to the text harder
Suppose your company’s name has been changed, and you have to change the wordings in your app.
- If you have hardcoded the entire text, you will need to edit a whole host of files to change the text.
So, what can be done?
The Solution
Put the string values in strings.xml rather than hardcoding them.
strings.xml is a resource file used to hold name/value pairs of strings.
How does it help?
It is much easier to internationalize an app with the help of a string resource file.
- You can easily replace the string.xml file with an internationalized version instead of having to edit the hardcoded text values in a whole host of numerous layout and activity files.
It also enhances the process of making global changes to the text across the application much efficient as you only need to edit a single file – strings.xml
Using String Resources
In order to use a string resource in your layout, there are two things you need to do:
- Create the string resource by adding it to strings.xml.
- Use the string resource in your layout.
Let us see how this is done.
String Resource Creation
We are going to create 4 string resources, one for the text that appears at the button, and three for the text that appears in the text view.
To do this, use Android Studio’s explorer to find the file strings.xml in the app > src > main > res > values folder.
The file should look similar to the following.
<resources>
<string name=”app_name”>WTWW</string>
</resources>
strings.xml contains a string resource named “app_name,” which has a value of WHAT THE WEIRD WORD!.
Android Studio creates the string resource automatically every time a new project is created.
App Continue..
Now, let’s get rid off all the hard-coded strings from activity_main.xml
To do this, add the following entries in strings.xml
<string name=”app_name”>WHAT THE WEIRD WORD!</string>
<string name=”next_weird_word”>NEXT WEIRD WORD</string>
<string name=”word_name_text”>Word Name</string>
<string name=”word_meaning”>Word Meaning </string>
Once you’ve updated the file, save the changes from the File menu.
String resources can be used in your layout as follows:
android:text=”@string/app_name”
As you already know, android:text specifies the text that is to be displayed.
But what does “@string/app_name” mean?
- Let’s start with the first part, @string.
- @string tells Android to look up a text value from the string resource file.
- In our case, this is the file strings.xml that you just edited.
- The second part is app_name.
- It tells Android to look up the value of a resource with the name app_label.
- So “@string/app_name” means “look up the string resource with the name app_label, and substitute app_label the associated text value.”
During test drive #1, when we launched the application, we were able to visualize the layout we designed for our app, that is, the UI components represented by the corresponding placeholders.
But when we first launch the application, we would want a weird word, and its meaning to be displayed on the screen.
To accomplish that there are two steps involved:
- We need to create references for the text views.
- Then, we need to set text in the text views.
Move along to find out “how-to”.
The Activity Code
When you create a new project, the wizard creates an empty activity called MainActivity. The code for this activity is held in a file called MainActivity.java.
Open this file from app > src > main > java folder.
You can see that Android Studio has generated Java code as follows.
package rishiz.site.whattheweirdword; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; x public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
MainActivity.java Deciphered
All activities (not just this one) must extend the Activity class or one of its subclasses.
The Activity class consists of a bunch of methods that enhance your Java class from a plain old Java class into a full-fledged, card-carrying Android activity.
All activities should also implement the onCreate() method.
- This method gets called when an object of the activity is created. It is used to perform basic setup, such as what layout the activity is associated with.
Bundle savedInstanceState – saves the state of the activity.
setContentView() – tells the activity which layout file to use for the screen. It parses the layout and creates a view hierarchy.
R.layout.activity_main – is the reference ID of the layout resource activitymain.xml.
- In the previous code, setContentView(R.layout.activity_main) tells Android that this activity uses activity_main as its layout.
Referencing a View
The first step to display the initial weird word is to create references for the text views.
We can get references for our GUI components using a method called findViewById().
This method takes the ID of the GUI component as a parameter and returns a View object.
Here is how you should use findViewById() to get a reference to the text view with an ID my_textView:
TextView myTextView = findViewById(R.id.my_textView);
Similarly, to get a reference to a button with an ID my_button:
Button myButton = findViewById(R.id.my_button);
.. What’s that “R”?
Take a closer look at how the ID of the text view was specified.
Instead of passing in the name of the text view, we passed in an ID of the form R.id.wordNameView.
So what does this mean? What’s R?
- R.java is a special Java file that gets generated by the Android Studio whenever you create or build your app.
- It can be found in the app > build > generated > source > r > debug folder in a package with the same name as the package of your app.
- Android uses R.java to keep track of the resources used within the app, and it enables you to get references to GUI components from within your activity code in other word Android R.java file contains resource IDs for all the resources we can use to access views from our java file.
Setting Text in the Text Views
The findViewById() method provides you a Java version of your GUI component.
This means that you can get and set properties in the GUI component using the methods exposed by the Java class.
Let us take a closer look.
Once you have referenced the text views, you can then call methods on the TextView objects.
For example, say, you want to set the text in my_textView to “Hello World.”
The TextView class includes a method called setText() that you can use to change the text property.
It can be used as:
myTextView.setText(“HelloWorld”);
For example, say, you want to set the text in my_textView to “Hello World.”
The TextView class includes a method called setText() that you can use to change the text property.
It can be used as:
myTextView.setText(“HelloWorld”);
Update the activity code to display the following details during the initial launch.
- Weird Word Name: Bumbershoot
- Weird Word Meaning: An umbrella.
Hint: Access the wordNameView and wordMeaningView in onCreate() method of ActivityMain.java and set their initial values.
Now that we have created our What The Weird Word app and set it to display the initial word,we are almost set to launch our application.
The only thing left it to get the button working in such a way that when “ NEXT WEIRD WORD” button is clicked,a random weired word,and its meaning would be display in the corresponding text views.
The Button
layout includes a button, something is expected to happen when a user clicks the button.
Buttons carry out the expected tasks by calling a corresponding method in the activity.
In our app, to get the button to call a method in the activity when it is clicked, we need to make changes to two files:
- Change the layout file XML.
Specify the method in the activity that will be called when the button is clicked.
2.Change the activity file java.
Define the method that gets called.
The onClick Attribute
It takes only one line of XML to tell Android the method a button will call when it is clicked.
All you have to do is add an android:onClick attribute to the <button> element and describe the name of the method that is to be called as shown as follows
android:onClick=”Method_Name”
Go to the layout file activity_main.xml, and add a new line of XML to the <button> element to say that the method displayWeirdWord should be called when the button is clicked.
Now that the layout knows which method to call in the activity, we need to define the method.
Implementing the Method
Once the onClick attribute is added to the button, the corresponding method should be added to the activity.
Doing so will enable the activity to respond when the user clicks the button in the user interface.
But there is a catch!
The displayWeirdWord() method needs to have a particular signature. Otherwise, it will not be called when the button specified in the layout gets clicked.
The method needs to take the following form.
public void displayWeirdWord(View view) {
}
To get a method to respond to a button click, it has to be made public, have a void return type, and take a single View parameter.
The View parameter in the method may seem unusual at first, but there is a good reason for it being there.
- This parameter refers to the GUI component that triggers the method (in this case, the button).
Note: As mentioned earlier, GUI components such as buttons and text views are all types of View.
Update the MainActivity.java file with the following code implementing the displayWeirdWord() method to display the next weird word.
public void displayWeirdWord(View view) {
word_name_view.setText(“Flawsome”);
word_meaning_view.setText(“An individual who embraces their flaws and knows they are awesome regardless”);
}
Note: Let us hardcode the words, for the time being, to ensure that everything is working as expected.
Alternative of onClick Attribute(good to use)
We can add click listeners by using set on click listener method as follows:
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Action here (this performed when button is clicked) } });
The Weird Word Deck Java Class
Rest assured that the core functionality is working, let us remove the hard-coded infestations from our app and organize the list of weird words in a deck.
Add a new java class – weirdWordDeck.java (in the same package as MainActivity.java)
- To add the new class, navigate to WTWW > app > src > main > java > rishiz.site.whattheweirdword
- Right-click the package name, select New > Java class
In the window that opens, name the new class as weirdWordDeck and click ok.
package rishiz.site.whattheweirdword; import androidx.annotation.NonNull; public class WeirdWordDeck { public static final String[] weirdWord = {"Collywobbles", "Gobbledygook", "Flummox", "Lollygag", "Kerfuffle", "Snickersnee"}; public static final String[] weirdWordMeaning = {"A feeling of discomfort or anxiety in the stomach.", " Language that is overly complex, technical, or difficult to understand", "To bewilder or confuse", " To spend time aimlessly, idly, or in a lazy manner ", "A commotion or fuss", "A large knife or a fight with knives"}; @NonNull public static String[] shuffleAndPick() { String[] word = new String[2]; int num = (int) (Math.random() * weirdWord.length); word[0] = weirdWord[num]; word[1] = weirdWordMeaning[num]; return word; } }
MainActivity – The Whole Picture
package rishiz.site.whattheweirdword; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView word; TextView meaning; Button btnNext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); word = findViewById(R.id.wordName); meaning = findViewById(R.id.wordMeaning); word.setText("Bumbershoot"); meaning.setText(" An umbrella"); } public void displayWeirdWord(View view) { String[] weirdWord = WeirdWordDeck.shuffleAndPick(); word.setText(weirdWord[0]); meaning.setText(weirdWord[1]); } }