Do you remember the alert() function from javascript, well something similar is back in Android but Google calls it the AlartDiaglog instead.
The Result

The alertdialog app: the button that triggers the alert
and when you click it…

the alert dialog that pops when you click the button
BAM!!!!
Your result will actually be different than mine since I added and "OK" button after I took the picture. I didn’t want to take another screenshot (with 1gb of ram and 7 programs running at once who would).
The Java Code (HelloAndroid.java)
package com.example.helloandroid; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.View; public class HelloAndroid extends Activity{ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void showAlert(View v){ AlertDialog.Builder alert=new AlertDialog.Builder(this); alert.setTitle("Alert!").setMessage("We are under attack!").setNeutralButton("OK", null).show(); } }
The setNeutralButton is optional, the null value could be replaced with a listener. There are other buttons you can set as well such as the positive and negative buttons.
The GUI (main.xml)
Just like in my previous tutorial we use the onClick attribute to set the function we call in the JAVA code.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click Me" android:onClick="showAlert"/> </LinearLayout>
The Manifest(AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.helloandroid" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="13" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true"> <activity android:name=".HelloAndroid" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>