Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Creating Alerts in SL4A

Author: Rachee Singh
Published? true
FormatLanguage: WikiFormat

Problem:

You need to create an alert box or pop-up dialog using Python in the Scripting Layer for Android (SL4A)

Solution:

There are many kinds of alert dialogs that can be created using Python in ASE. They can have buttons, lists etc.

Discussion:

  • Start the ASE app on your emulator/phone.
  • Add a new python script my clicking the menu button and choosing 'Add'.

Choose Python 2.x option from the submenu that appears, like this:

  • This opens an editor. Enter the name of the script (I have named it alertdialog.py).

  • Now we are ready to put in the code to create Alert dialogs. Type in this code:
	
  title = 'Sample Alert Dialog'
  text = 'Alert Dialog Type 1!'
  droid.dialogCreateAlert(title, text)
  droid.dialogSetPositiveButtonText('Continue')
  droid.dialogShow()
  • Press the menu button and choose 'Save and Run' from the menu. This runs the script and this is how the alert dialog looks:

  • Similarly, try this type of alert dialog. On running you will see and alert dialog with 2 buttons:
  title = 'Sample Alert Dialog'
  text = 'Alert Dialog Type 2 with Buttons!'
  droid.dialogCreateAlert(title, text)
  droid.dialogSetPositiveButtonText('Yes')
  droid.dialogSetNegativeButtonText('No')
  droid.dialogSetNeutralButtonText('Cancel')
  droid.dialogShow()

Here is how the alert dialog looks:

Also try this code to create an alert dialog with a list:

  title = 'Sample Alert Dialog'
  droid.dialogCreateAlert(title)
  droid.dialogSetItems(['mango', 'apple', 'strawberry'])
  droid.dialogShow()

Here is how the alert dialog looks:

No records found.