How to Build a Simple Magic 8 Ball App in Android?
In this article, we will be building a Magic 8 Ball App Project using Java and XML in Android. The application is based on a decision making application. In this app, a user can ask the ball what decision they should make. The ball will randomly answer Yes, No, Not Sure, and other such answers. There will be a single activity in this application. A sample GIF is given below to get an idea about what we are going to do in this article.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Before going to the coding section first you have to do some pre-task
Ball Images: All the ball images are listed below. Save them in your drawable folder in resources. Go to the app > res > drawable and paste the following files:
Change the style to NoActionBar in the themes.xml file:
<style name=”AppTheme” parent=”Theme.AppCompat.NoActionBar”>
Step 3: Working with the activity_main.xml file
The XML codes are used to build the structure of the activity as well as its styling part. It contains a TextView at the very top of the activity to display the title. Then it contains an ImageView of the ball in the center of the activity. At last, we have a Button at the bottom of the activity for asking the application to make decisions. This is a single activity application. Below is the code for the activity_main.xml file.
Step 4: Working with the MainActivity.java file
In the java file we will create an onClickListener() function for the ask button also we will create an array to store the id of all the images. Inside the onClickListener() we will generate a random number from 1-4 using the Random() function. After that, we will set the image from the array of random number’s position in the image view. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.