Skip to content

Instantly share code, notes, and snippets.

@erickvieira
Last active May 8, 2018 20:28
Show Gist options
  • Save erickvieira/3f41d137cf5229b5a1509d3e15a97576 to your computer and use it in GitHub Desktop.
Save erickvieira/3f41d137cf5229b5a1509d3e15a97576 to your computer and use it in GitHub Desktop.
[ANDROID][ALERTDIALOG][KOTLIN] An Android Native alert builder code: this code contains two classes that abstracts the usage of AlertDialog class in AndroidStudio projects. Obs.: The third file is an implementation example, it helps you to learn the right idealized usage.
// package com.example.user.project // REPLACE THIS LINE BY YOUR PACKAGE
import android.support.annotation.DrawableRes
import com.example.edmilton.prototipoamerica.R
enum class AlertType(@DrawableRes internal val path: Int) {
// THAT IS ONLY AN EXAMPLE, YOU CAN REPLACE WITH YOUR ICONS FILE NAMES
WARNING(R.drawable.ic_warning),
SUCCESS(R.drawable.ic_success),
INFO(R.drawable.ic_info),
ERROR(R.drawable.ic_error),
TIMEOUT(R.drawable.ic_timeout),
SECURITY(R.drawable.ic_security);
}
// package com.example.user.project // REPLACE THIS LINE BY YOUR PACKAGE
// IT IS AN MOTHERF***R ALERTCONTROLER B**CHES
// 😎/\😎
// seriously, you dont really need to understad imports, ignore that
import android.app.Activity
import android.content.Intent
import android.support.v7.app.AlertDialog
//import com.example.user.project.R
//import com.example.user.project.AlertType.* // pakage reference here, you need to change it
typealias Method = () -> Unit // abstraction to method with no params and void return in Kotlin syntaxe
class EasyAlerts {
private var alert: AlertDialog? = null // null is used here like a flag -> indicates that alert is not in use yet
fun showGenericNeutralAlert(
type: AlertType?, // I like to use icons in my alerts, so if you too, first lear how to add it in your project using AndroidStudio assets manager to include image assets (the icons here)
title: String, // a flashy title
msg: String, // the alert body message
currentActivity: Activity, // the activity that invokes this alert
callback: Method? // using JavaScript-like callbacks approach, if you dont know it, search the concept before
) {
if (alert != null) { alert!!.dismiss(); alert = null }
// basically non null alert means that this class is in use now, so we need to dismiss it to avooid alert cascade on screen
// setting the attributes, it speak by itself, I hope :D
val alertBuilder = android.support.v7.app.AlertDialog.Builder(currentActivity)
alertBuilder.setIcon(type?.path ?: INFO.path)
alertBuilder.setTitle(title.toUpperCase())
alertBuilder.setMessage(msg)
alertBuilder.setNeutralButton("Ok") {
_,
_ ->
// so, if you followed my advice about JavaScript-like callbacks, It will help you
// this lambda expretion provides us the power to implements an function inside the alert action (since it dont needs params)
if (callback != null) {
callback()
} else alert!!.dismiss() // if you dont like this shit, no problem, calls this method only passing null instead callback variable
}
// no secrets here, it presents the alert on the screen
alert = alertBuilder.create()
alert!!.setCancelable(false)
alert!!.show()
// wow, that is it, you now have an alert on the device screen without any concerns about this AlertBuilder stuff ;)
}
fun showNeutralAlertToOpenActivity(
type: AlertType?,
title: String,
msg: String,
currentActivity: Activity,
targetActivity: Class<*>? // if you have an java class that would uses this AlertController
) {
if (alert != null) { alert!!.dismiss(); alert = null }
val alertBuilder = android.support.v7.app.AlertDialog.Builder(currentActivity)
alertBuilder.setIcon(type?.path ?: INFO.path)
alertBuilder.setTitle(title.toUpperCase())
alertBuilder.setMessage(msg)
alertBuilder.setNeutralButton("Ok") {
_,
_ ->
if (targetActivity != null) {
val intent = Intent(currentActivity.baseContext, targetActivity)
currentActivity.startActivity(intent)
currentActivity.finish()
}
alert!!.dismiss()
}
alert = alertBuilder.create()
alert!!.setCancelable(false)
alert!!.show()
}
// the same stuff but with 2 buttons (logic decision)
fun showGenericDecisionAlert(
type: AlertType?,
title: String,
msg: String,
currentActivity: Activity,
positiveCallback: Pair<String, Method>?,
negativeCallback: Pair<String, Method>?
) {
if (alert != null) { alert!!.dismiss(); alert = null }
val alertBuilder = android.support.v7.app.AlertDialog.Builder(currentActivity)
alertBuilder.setIcon(type?.path ?: INFO.path)
alertBuilder.setTitle(title.toUpperCase())
alertBuilder.setMessage(msg)
alertBuilder.setPositiveButton(positiveCallback?.first ?: "Yes") {
_,
_ -> if (positiveCallback != null) {
positiveCallback.second()
} else alert!!.dismiss()
}
alertBuilder.setNegativeButton(negativeCallback?.first ?: "No") {
_,
_ -> if (negativeCallback != null) {
negativeCallback.second()
} else alert!!.dismiss()
}
@Suppress("DEPRECATION")
alert!!.getButton(android.app.AlertDialog.BUTTON_POSITIVE).setTextColor(currentActivity.resources.getColor(R.color.colorPrimary))
alert = alertBuilder.create()
alert!!.setCancelable(false)
alert!!.show()
}
}
//====================================================== EXAMPLES ======================================================
//= JAVA EXAMPLE =======================================================================================================
/*
someButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AlertModels().showNeutralAlertToOpenActivity(
AlertType.SUCCESS,
"A COOL TITLE",
"This is an Easy Alert, motherf**ckers",
(Activity) v.getContext(),
AnotherActivity.class
);
}
});
*/
//======================================================================================================================
//= KOTLIN EXAMPLE =====================================================================================================
val alert = EasyAlerts()
alert.showGenericNeutralAlert(
AlertType.SUCCESS,
"A COOL TITLE",
"This is an Easy Alert, motherf**ckers",
this@AnotherActivity,
fun() { // on the fly function that implements an method to clear my EditTexts contents
myEditText1.setText("")
myEditText2.setText("")
}
)
//======================================================================================================================
//= KOTLIN EXAMPLE =====================================================================================================
val myAlertModel: () -> Unit = {
EasyAlerts().showGenericNeutralAlert(
AlertType.SUCCESS,
"A COOL TITLE",
"This is an Easy Alert, motherf**ckers",
this@AnotherActivity,
clearMyEditTexts // remember to do not implements the method (using '()' sufix), we need a method template, not an implementation
)
}
val clearMyEditTexts: () -> Unit = {
myEditText1.setText("")
myEditText2.setText("")
}
//======================================================================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment