Hello,
When you start to learn Android Development, it can be interesting to make some little and fun applications. It’s good to motivate yourself and it is also a great way to discover some specific part of the Android SDK. Today, I propose you to create a Flip Coin Application on Android to help you to discover how to use the Animation API.
Note that you can discover this tutorial directly in video on Youtube :
To create a Flip Coin Application, the first thing is to have two images for the head and the tail of the coin. We will use a Minnesota Quarter Coin here :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
The second step is to define an ImageView and a Button in the layout of the Main Activity :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.coinflip.MainActivity">
<ImageView
android:id="@+id/coin"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/heads"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/coin"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="Flip"/>
</RelativeLayout>
Now, we can write the Java code. The most interesting part of our application is implemented in the flipCoin() method. We create two animations :
- A Fade Out animation to let the coin disappear when the user will click on the button to flip the coin
- A Fade In animation to let the coin appear after we flip the coin randomly
The Fade Out and Fade In animations are created via the AlphaAnimation class on Android. We are going to animate the alpha property from 1 to 0 for the Fade Out effect and then from 0 to 1 for the Fade In effect.
We add an AnimationListener on the Fade Out animation to be sure to flip the coin and to start the Fade In animation just when the Fade Out effect will be ended.
The code for the Main Activity will have the following form :
Code:
package com.ssaurel.coinflip;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public static final Random RANDOM = new Random();
private ImageView coin;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coin = (ImageView) findViewById(R.id.coin);
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
flipCoin();
}
});
}
private void flipCoin() {
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(1000);
fadeOut.setFillAfter(true);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
coin.setImageResource(RANDOM.nextFloat() > 0.5f ? R.drawable.tails : R.drawable.heads);
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator());
fadeIn.setDuration(3000);
fadeIn.setFillAfter(true);
coin.startAnimation(fadeIn);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
coin.startAnimation(fadeOut);
}
}
Now, you can run the application and enjoy the final result :
Don't hesitate to give it a try and give your feedbacks.
Thanks.
Sylvain
nice
Related
Hello,
I create this thread to present you a tutorial learning you how to create a Magnetometer Metal Detector App for Android. You can also discover this tutorial in video on Youtube :
Learn to create a Magnetometer Metal Detector on Android
Manufacturers continuously add more features and sensors to smartphones. Thus, your smartphone has now a magnetic field sensor which can help you to use your smartphone as a Magnetometer Metal Detector. For example, we have published an application of this kind on the Google Play Store : https://play.google.com/store/apps/details?id=com.ssaurel.magnetometer
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Magnetometer Metal Detector lets you to measure magnetic field around you by using the magnetic sensor that is built into your smartphone and tablet. It helps you to detect metal objects (steel, iron) around you. When a metal object is near to you, the magnetic field level will increase. Note that gold, silver an copper coins cannot be detected since they are classified as non-ferrous metal and so, they have no magnetic field.
In this tutorial, you are going to learn how to create a Magnetometer Metal Detector application like this we have published on the Google Play Store. First, you need to create a simple layout with a TextView widget centered on the screen :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="#000000"
tools:context="com.ssaurel.magnetometerapp.MainActivity">
<TextView
android:id="@+id/value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="45.00"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:textSize="23sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Now, it’s time to go on your main Activity to write Java code. First, you need to implement the SensorEventListener interface to register to know Magnetic Field sensor values. You will get values on three axes : X, Y and Z. To determine the magnetic field value, you will need to apply a mathematic formula :
Magnetic Value = sqrt(Value_X * Value_X + Value_Y * Value_Y + Value_Z * Value_Z)
Thus, the magnetic value is equal to the square root of the sum of squared values on each axes. Code for the Activity will have the following form :
Code:
package com.ssaurel.magnetometerapp;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
private TextView value;
private SensorManager sensorManager;
public static DecimalFormat DECIMAL_FORMATTER;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = (TextView) findViewById(R.id.value);
// define decimal formatter
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator('.');
DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// get values for each axes X,Y,Z
float magX = event.values[0];
float magY = event.values[1];
float magZ = event.values[2];
double magnitude = Math.sqrt((magX * magX) + (magY * magY) + (magZ * magZ));
// set value on the screen
value.setText(DECIMAL_FORMATTER.format(magnitude) + " \u00B5Tesla");
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
By reading this code, you can note that the Sensor Service is retrieved on the onCreate method. Then, we register our Activity to listen changes of values for the Magnetic Field sensor by calling the registerListener method of the SensorManager instance retrieved previously. We choose also the delay to get update of magnetic field values. When the application is paused, we unregister the listener.
Now, you can launch your application to try your Magnetometer Metal Detector :
That’s all for this tutorial. You can know make your own Magnetometer Metal Detector and improve it by adding a graph to show recent magnetic field activity or a Gauge View to display the magnetic field value like on the version published on the Google Play Store. You can show the application in action in this demo video :
Thanks.
Sylvain
Hello,
I create that thread to present you a tutorial learning you how to Auto Restart an Android App after a Crash or a Force Close Error. You can also discover this tutorial and the demo video associated directly on Youtube :
How to auto restart an Android Application after a Crash or a Force Close Error ?
The biggest nightmare of Android developers is the Crash or Force Close Error that can occur when a user uses one of their applications. Indeed, it’s always a bad message sent to the user and the major risk is that the user uninstalls the application. Unfortunately, you can’t always catch properly all errors and sometimes you can’t avoid a Crash or a Force Close Error. In these specific cases, a good approach is to configure auto restart for your Android Application. With this approach, you have better chances to keep users on your application.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
To start, you need to create a custom Application class implementation to get an instance of your context continuously :
Code:
package com.ssaurel.appcrash;
import android.app.Application;
import android.content.Context;
public class MyApplication extends Application {
public static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
@Override
public Context getApplicationContext() {
return super.getApplicationContext();
}
public static MyApplication getInstance() {
return instance;
}
}
Don’t forget to add this Application implementation on your Android Manifest :
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ssaurel.appcrash">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name=".MyApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
To try the auto restart feature, we need to define a button in the layout of the Main Activity. When we will click on the button, we’re going to crash the application. The layout will have the following form :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.appcrash.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Crash Me !"
android:onClick="crashMe"/>
</RelativeLayout>
Now, we enter in the core of our auto restart feature. You need to create a custom implementation of the UncaughtExceptionHandler interface. What is the purpose of this interface ? It’s an interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
Our custom implementation will have the following form :
Code:
package com.ssaurel.appcrash;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {
private Activity activity;
public MyExceptionHandler(Activity a) {
activity = a;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
Intent intent = new Intent(activity, MainActivity.class);
intent.putExtra("crash", true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(MyApplication.getInstance().getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager mgr = (AlarmManager) MyApplication.getInstance().getBaseContext().getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent);
activity.finish();
System.exit(2);
}
}
When an uncaught exception occurs, the uncaughtException method will be called. We’re going to create an Intent to restart our application at the defined moment via an Alarm. Then, we finish the current activity and we exit the application. Note that we put a boolean parameter to indicate that the application is restarted.
Last step is to install the UncaughtExceptionHandler during the start of the application by calling the static setDefaultUncaughtExceptionHandler method of the Thread class :
Code:
package com.ssaurel.appcrash;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this));
if (getIntent().getBooleanExtra("crash", false)) {
Toast.makeText(this, "App restarted after crash", Toast.LENGTH_SHORT).show();
}
}
public void crashMe(View v) {
throw new NullPointerException();
}
}
Note that we launch a NullPointerException in the crashMe method to force the crash of the application and test the auto restart feature. Other thing to note is the crash boolean parameter test when the activity is launched. Like said previously, it lets us to know when the application is restarted after a crash or when the application is launched for the first time.
Now, you can launch the application and you should see the following screen after a click on the crashMe button :
Don't hesitate to give it a try and give me your feedbacks if you have some ideas for new tutorials.
Thanks.
Sylvain
Really good guide, it resembles an implementation I had of a simple "restart" feature in my app. Only thing I'm wondering is why does System.exit if given enough time before the activity is restarted (in my case roughly AlarmManager.RTC, System.currentTimeMillis() + ~ 1.5 seconds) will display the annoying "Unfortunately XYZ has stopped" and prevent the application from fully starting until OK is clicked? Is there any potential risk or downside to setting the alarm manager delay to only +100? I'm thinking something along the lines of not enough time to flush resources?
Hello,
I create that thread to present you a tutorial learning you to use OkHttp to make Network Requests on Android. Note that you can enjoy this tutorial in video on Youtube :
Created by Square, OkHttp is an open source project designed to be an efficient HTTP and HTTP/2 client. It lets you to make fast requests and save bandwith. It offers some great features out of the box like to share a socket for all HTTP/2 requests to the same host, a connection pooling mechanism when HTTP/2 is not available, transparent GZIP feature to reduce download sizes and a caching mechanism for responses. Besides, OkHttp has a great mechanism to manage common connection problems. And now, it supports also WebSocket.
OkHttp offers a request / response API that makes developers life easier. It supports synchronous and asynchronous calls. Even better, OkHttp is also available for Java projects with Java 7 as requirement.
First you need to add the following dependency to your build.gradle file :
Code:
compile 'com.squareup.okhttp3:okhttp:3.5.0'
For our example, we are going to consume a simple JSON Rest Web Service from the SSaurel’s Website : http://www.ssaurel.com/tmp/todos . So, we are going to create a simple layout with a Button to start the network request and a TextView to display the date got from the Web Service :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.okhttptut.MainActivity">
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"
android:text="Get WebService"/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result ..."
android:layout_centerHorizontal="true"
android:textSize="17sp"
android:layout_below="@id/getBtn"
android:layout_marginTop="20dp"/>
</RelativeLayout>
Now, it’s time to write the Java code to make the Network Request by using the OkHttp API. First, we create the OkHttpClient instance. Then, we need to create the request via the Request object and its Builder class. Next step is to pass the request in parameter of the newcall method of the OkHttpClient instance created. OkHttp supports asynchronous and synchronous calls. Here, we are going to use asynchronous request so we call the enqueue method. It takes a Callback object in parameter which has two methods : onFailure and onResponse. Note that these methods are executed in a separate thread. So, if you want to update your User Interface with data got from the Network inside this method, you must embed this in a runOnUiThread call to ensure the update will be made on the UI Thread.
The Java code to consume the JSON Web Service with OkHttp will have the following form :
Code:
package com.ssaurel.okhttptut;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Button getBtn;
private TextView result;
private OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getWebservice();
}
});
client = new OkHttpClient();
}
private void getWebservice() {
final Request request = new Request.Builder().url("http://www.ssaurel.com/tmp/todos").build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
result.setText("Failure !");
}
});
}
@Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error during get body");
}
}
});
}
});
}
}
Now, you can try your application and you should obtain the following result by clicking on the Get WebService button :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Don't hesitate to give it a try to this tutorial and give me your feedbacks. To discover more tutorial on Android development, you can read my blog : https://www.ssaurel.com/blog
Thanks.
Sylvain
Hello,
I create that thread to present you a tutorial learning you to create the game "Spin The Bottle" for Android. It is also a good way to discover how to use Android Animations API.
What is better that creating some funny games to learn the basics of Android development ? Today, you’re going to discover more on the Android Animation API by creating the game “Spin The Bottle”.
Note that you can discover this tutorial in video on Youtube too :
Spin the bottle is a party game in which several players sit/stand/kneel in a circle. A bottle is placed on the floor in the center of the circle. A player spins the bottle, and must kiss the person to whom the bottle points when it stops spinning.
With our application, it is not necessary any more to have a real bottle, you will just need a smartphone. And it’s great because everyone has always a smartphone on him nowadays.
First step is to find two specific images : one for the floor which will be defined as background of the game and an other for the bottle which will be rotated during the game.
We have chosen to use these both images :
Floor image for the background
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Bottle image
Now, we need to define the layout of our game “Spin The Bottle”. We have a Relative Layout with the floor image as background and we add a bottle in the center of this layout :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background">
<ImageView
android:id="@+id/bottle"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/beer_bottle"
android:layout_centerInParent="true" />
</RelativeLayout>
The next step is to write the Java code of the Main Activity. First, we get references for the views. Then, we install a click listener on the main layout of the Main Activity. Thus, the user will just have to touch the screen to spin the bottle and to start the game.
The core of the game is in the spinTheBottle() method. We are going to define a RotateAnimation from start angle to end angle centered on the center of the bottle. The end angle will be defined randomly to simulate really the game “Spin The Bottle”. We should store the last end angle value to restart the bottle in the same position for the next turn of the game.
The Code of the Main Activity will have the following form :
Code:
package com.ssaurel.spinthebottle;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
public static final Random RANDOM = new Random();
private View main;
private ImageView bottle;
private int lastAngle = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main = findViewById(R.id.root);
bottle = (ImageView) findViewById(R.id.bottle);
main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
spinTheBottle();
}
});
Toast.makeText(this, R.string.touch_to_spin, Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_spin :
spinTheBottle();
break;
case R.id.action_zero :
resetTheBottle();
break;
}
return super.onOptionsItemSelected(item);
}
private void spinTheBottle() {
int angle = RANDOM.nextInt(3600 - 360) + 360;
float pivotX = bottle.getWidth() / 2;
float pivotY = bottle.getHeight() / 2;
final Animation animRotate = new RotateAnimation(lastAngle == -1 ? 0 : lastAngle, angle, pivotX, pivotY);
lastAngle = angle;
animRotate.setDuration(2500);
animRotate.setFillAfter(true);
bottle.startAnimation(animRotate);
}
private void resetTheBottle() {
float pivotX = bottle.getWidth() / 2;
float pivotY = bottle.getHeight() / 2;
final Animation animRotate = new RotateAnimation(lastAngle == -1 ? 0 : lastAngle, 0, pivotX, pivotY);
lastAngle = -1;
animRotate.setDuration(2000);
animRotate.setFillAfter(true);
bottle.startAnimation(animRotate);
}
}
You can run the application and play your game :
To go further, you can download the game “Spin The Bottle” created in this tutorial on the Google Play Store :
https://play.google.com/store/apps/details?id=com.ssaurel.spinthebottle
Hello,
In that tutorial, you are going to learn how to create an Anagram game for Android by using Android Studio.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
But what is an Anagram ?
An anagram is direct word switch or word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example, the word anagram can be rearranged into “nag a ram”.
Note that you can discover this tutorial in video on YouTube :
Create the User Interface
To start, we are going to create the User Interface of our Anagram game. In our User Interface, we will have a TextView to display the anagram. Then, an EditText to let the users to enter the word they found. And finally both buttons : one to validate the word entered and another to start a new game.
We make some customizations on these views. For example, we center them horizontally and this gives us the following code :
Code:
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/wordTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Word To Find"
android:textSize="22sp"
android:textStyle="bold" />
<EditText
android:id="@+id/wordEnteredEt"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/wordTv"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:inputType="textCapCharacters" />
<Button
android:id="@+id/validate"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/wordEnteredTv"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="Validate" />
<Button
android:id="@+id/newGame"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_below="@id/validate"
android:layout_centerHorizontal="true"
android:layout_marginTop="25dp"
android:text="New Game" />
</RelativeLayout>
Core of the Anagram Game
Now, we can create the core of our game : the Anagram class. We will use this class to generate new words to find and to shuffle the word to find. Note that the list of words used for the game will be defined in this class :
Code:
package com.ssaurel.anagram;
import java.util.Random;
/**
* Created by ssaurel on 05/09/2017.
*/
public class Anagram {
public static final Random RANDOM = new Random();
public static final String[] WORDS = {"ACCOUNT", "ADDITION",
"AGREEMENT", "ANGRY", "ANIMAL", "BEHAVIOUR", "BETWEEN", "BLACK", "CHEMICAL", "FOOLISH",
"FREQUENT", "GOVERNMENT", "GRAIN", "GRASS", "HOSPITAL", "PAYMENT", "POLITICAL",
"PROCESS", "SHAME", "SMASH", "SMOOTH", "STATEMENT", "SUBSTANCE", "TEACHING", "TENDENCY",
"TOMORROW", "TOUCH", "UMBRELLA", "WEATHER", "YESTERDAY"};
public static String randomWord() {
return WORDS[RANDOM.nextInt(WORDS.length)];
}
public static String shuffleWord(String word) {
if (word != null && !"".equals(word)) {
char a[] = word.toCharArray();
for (int i = 0; i < a.length; i++) {
int j = RANDOM.nextInt(a.length);
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return new String(a);
}
return word;
}
}
Code of the Main Activity
Now, we can write the Java code of the main activity. The code is pretty simple. We get references of the views in the onCreate method. Then we install OnClickListener for both buttons.
In the validate method, we are going to check if the word entered by the user if equal to the word to find. If yes, we display a message of congratulations to the user and we start a new game by calling the newGame method.
The newGame method is used to start a new Anagram game. We generate a random word to find by calling the randomWord method of the Anagram class. Then, we shuffle this word via the shuffleWord method of the Anagram class. Finally, we display the word shuffled on the screen. The game starts and the user must find the word.
This gives us the following code :
Code:
package com.ssaurel.anagram;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private TextView wordTv;
private EditText wordEnteredTv;
private Button validate, newGame;
private String wordToFind;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wordTv = (TextView) findViewById(R.id.wordTv);
wordEnteredTv = (EditText) findViewById(R.id.wordEnteredEt);
validate = (Button) findViewById(R.id.validate);
validate.setOnClickListener(this);
newGame = (Button) findViewById(R.id.newGame);
newGame.setOnClickListener(this);
newGame();
}
@Override
public void onClick(View view) {
if (view == validate) {
validate();
} else if (view == newGame) {
newGame();
}
}
private void validate() {
String w = wordEnteredTv.getText().toString();
if (wordToFind.equals(w)) {
Toast.makeText(this, "Congratulations ! You found the word " + wordToFind, Toast.LENGTH_SHORT).show();
newGame();
} else {
Toast.makeText(this, "Retry !", Toast.LENGTH_SHORT).show();
}
}
private void newGame() {
wordToFind = Anagram.randomWord();
String wordShuffled = Anagram.shuffleWord(wordToFind);
wordTv.setText(wordShuffled);
wordEnteredTv.setText("");
}
}
Play to our Anagram Game
Now, it’s time to play to our Anagram Game. We launch the Anagram Game on an Android device and we see the following screen :
We have to enter the word to find in the EditText and then clicking to the validate button to win the game.
That’s all for that tutorial. To discover more tutorials on Android Development, don’t hesitate to subscribe to the SSaurel’s Channel on YouTube : https://www.youtube.com/channel/UCXoh49OXVg1UGjgWX1JRvlw
You can also discover this tutorial directly on the SSaurel's Blog : https://www.ssaurel.com/blog/learn-to-create-an-anagram-game-for-android/
Don't hesitate to give it a try and give me your feedback.
Thanks.
Sylvain