Skip to content

Instantly share code, notes, and snippets.

@prbale
Last active December 11, 2017 16:01
Show Gist options
  • Save prbale/04b76889806c2e62957bc3d47090888b to your computer and use it in GitHub Desktop.
Save prbale/04b76889806c2e62957bc3d47090888b to your computer and use it in GitHub Desktop.
Kotlin Useful Extensions
/**
* The `fragment` is added to the container view with id `frameId`.
* The operation is performed by the `fragmentManager`.
*/
fun AppCompatActivity.addFragment(
fragmentManager: FragmentManager,
fragment: Fragment,
frameId: Int) {
kotlin.checkNotNull(fragmentManager)
kotlin.checkNotNull(fragment)
val transaction = fragmentManager.beginTransaction()
transaction.add(frameId, fragment)
transaction.commit()
}
/**
* Activity extension function to hide keyboard
*/
fun AppCompatActivity.hideKeyboard() {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), 0);
}
/**
* Activity extension function to set full screen activity
*/
fun AppCompatActivity.setFullScreen() {
requestWindowFeature(Window.FEATURE_NO_TITLE)
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
/**
* Context extension to check network available or not.
*/
fun Context.isNetworkConnected(): Boolean {
val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork = cm.activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnectedOrConnecting
}
/**
* Context extension to inflate the layout.
*/
fun Context.inflateLayout(resource: Int, root: ViewGroup? = null, attachToRoot: Boolean = false): View {
return LayoutInflater.from(this).inflate(resource, root, attachToRoot)
}
inline fun Context.alert(func: AlertDialog.Builder.() -> AlertDialog.Builder) {
AlertDialog.Builder(this).func().show()
}
fun Context.toastShort(text: CharSequence) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
fun Context.toastShort(resId: Int) = Toast.makeText(this, resId, Toast.LENGTH_SHORT).show()
fun Context.toastLong(text: CharSequence) = Toast.makeText(this, text, Toast.LENGTH_LONG).show()
fun Context.toastLong(resId: Int) = Toast.makeText(this, resId, Toast.LENGTH_LONG).show()
fun String.isEmailValid(): Boolean {
val emailPattern = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
val pattern: Pattern = Pattern.compile(emailPattern)
val matcher: Matcher = pattern.matcher(this)
return matcher.matches()
}
fun String.upperCaseFirstLetter(): String {
return this.substring(0, 1).toUpperCase().plus(this.substring(1))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment