User Interactions in Android

User Interactions in Android

Toast Messages in Android

A Toast is a simple popup message in Android.

Image of Android device showing a toast popup reading
            'Sending message' next to an app icon

We use the maketext() method to instantiate a Toast, and show() method to display the Toast.

//Toast.makeText(context, text, duration).show()
Toast.makeText(this, "Sending message...", Toast.LENGTH_SHORT).show()

SnackBar Message in Android

A SnackBar Message shows a brief message at the bottom of the screen.

We use the make() method to instantiate a Snackbar, and show() method to display the Toast.

The setAction() method can be used to display an action button on the snackbar, however, it is optional.

Snackbar.make(myLayout,"Compose Snackbar Scaffold",Snackbar.LENGTH_LONG)
//where myLayout is reffered to our Layout View, applied on the Activity 
         .setAction("Done",View.OnClickListener{ 
//runs when Done Option selected in snackbar message
} }).show()

Dialog Messages in Android

A dialog is a small window that prompts the user to make a decision or enter additional information.

We create an AlertDialog by creating an object of the inner class of the AlertDialog class, which is the Builder class. The Builder class takes only one parameter i.e. the context.

val alertDialogMsg = AlertDialog.Builder(this@MainActivity)
//as we are inside an inner class we need to specify MainActivity with this

We can use methods like setTitle(), setIcon(), etc. to define our AlertDialog Object.

alertDialogMsg.setTitle("Alert !")
              .setMessage("Do you want to exit ?")
              .setCancellable(false)
//makes the dialog message compulsory to answer, can't back
              .setNegativeButton("NO", DialogInterface.OnClickListener{dialogInterface, i ->
//where dialogInterface represents our dialog object &
//i represents the index of the option selected No - 0 here 
              dialogInterface.cancel() 
              })  
              .setPositiveButton("YES", DialogInterface.OnClickListener{dialogInterface, i ->
              })
              .create().show()