Skip to content

Instantly share code, notes, and snippets.

@albertogiunta
Created March 20, 2018 10:30
Show Gist options
  • Select an option

  • Save albertogiunta/106c22303f4a7ba87f76a5ceef2180eb to your computer and use it in GitHub Desktop.

Select an option

Save albertogiunta/106c22303f4a7ba87f76a5ceef2180eb to your computer and use it in GitHub Desktop.
Extension functions (Kotlin) & build.gradle files for Android projects
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
androidExtensions { experimental = true }
android {
kapt { generateStubs = true }
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
// kotlin
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
// firebase
implementation "com.android.support:support-v4:$support_version"
implementation "com.google.firebase:firebase-core:$firebase_version"
implementation "com.google.firebase:firebase-ads:$firebase_version"
implementation "com.google.firebase:firebase-crash:$firebase_version"
implementation "com.google.android.gms:play-services-ads:$firebase_version"
// utility
implementation "co.trikita:log:$log_version"
implementation "com.github.apl-devs:appintro:v$appintro_version"
implementation "com.chibatching.kotpref:kotpref:$kotpref_version"
implementation "com.chibatching.kotpref:enum-support:$kotpref_version"
implementation "com.chibatching.kotpref:gson-support:$kotpref_version"
implementation "com.google.code.gson:gson:$gson_version"
implementation "com.beust:klaxon:$klaxon_version"
implementation "net.danlew:android.joda:$joda_version"
implementation "org.jetbrains.anko:anko:$anko_version"
implementation "org.jetbrains.anko:anko-design:$anko_version" // For SnackBars
// room
implementation "android.arch.persistence.room:runtime:$room_version"
implementation "android.arch.persistence.room:rxjava2:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
kapt "android.arch.persistence.room:compiler:$room_version"
// rxJava
implementation "io.reactivex.rxjava2:rxjava:$rxjava_version"
implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version"
// networking
implementation("com.squareup.retrofit2:retrofit:$retrofit_version") { exclude module: 'okhttp' }
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version"
implementation "com.squareup.picasso:picasso:$picasso_version"
implementation "org.jsoup:jsoup:$jsoup_version"
// design
implementation "com.android.support:recyclerview-v7:$support_version"
implementation "com.android.support.constraint:constraint-layout:$contraintlayout_version"
implementation "com.android.support:cardview-v7:$support_version"
implementation "com.android.support:design:$support_version"
implementation "com.android.support:support-emoji:$support_version"
// AndroidJUnitRunner and JUnit Rules
testImplementation "junit:junit:$junit_version"
androidTestImplementation "com.android.support.test:runner:$runner_version"
androidTestImplementation 'com.android.support.test:rules:$runner_version'
// Espresso dependencies
androidTestImplementation ('com.android.support.test.espresso:espresso-core:$espresso_version')
androidTestImplementation ('com.android.support.test.espresso:espresso-contrib:$espresso_version')
androidTestImplementation ('com.android.support.test.espresso:espresso-intents:$espresso_version')
androidTestImplementation ('com.android.support.test.espresso:espresso-accessibility:$espresso_version')
androidTestImplementation ('com.android.support.test.espresso:espresso-web:$espresso_version')
androidTestImplementation ('com.android.support.test.espresso.idling:idling-concurrent:$espresso_version')
androidTestImplementation 'com.android.support.test.uiautomator:uiautomator-v18:$uiautomator_version'
// The following Espresso dependency can be either "compile" or "androidTestCompile", depending on your app's implementation
androidTestCompile 'com.android.support.test.espresso:espresso-idling-resource:3.0.1'
}
afterEvaluate {
compileDebugAndroidTestKotlin.dependsOn assembleDebug
}
apply plugin: 'com.google.gms.google-services'
buildscript {
ext.support_version = '27.0.2'
ext.gradle_version = '3.0.1'
ext.kotlin_version = '1.2.21'
ext.gms_version = '3.1.1'
ext.firebase_version = '11.8.0'
ext.klaxon_version = '2.1.4'
ext.appintro_version = '4.2.2'
ext.kotpref_version = '2.2.0'
ext.anko_version = '0.10.3'
ext.log_version = '1.1.5'
ext.joda_version = '2.9.5.1'
ext.room_version = '1.0.0'
ext.rxjava_version = '2.1.7'
ext.rxandroid_version = '2.0.1'
ext.retrofit_version = '2.3.0'
ext.okhttp_version = '3.9.1'
ext.picasso_version = '2.5.2'
ext.jsoup_version = '1.11.2'
ext.gson_version = '2.8.1'
ext.design_version = '26.1.0'
ext.contraintlayout_version = '1.0.2'
ext.junit_version = '4.12'
ext.runner_version = '1.0.1'
ext.espresso_version = '3.0.1'
ext.uiautomator_version = '2.1.2'
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:$gradle_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.gms:google-services:$gms_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
/**
* ANY
*/
fun Any.toJson(): String = GsonInitializer.toJson(this)
/**
* VIEW
*/
fun View.toggleVisibility(setAsVisible: Boolean) = if (setAsVisible) this.visible() else this.gone()
fun View.toggleVisibility() = if (this.visibility == View.VISIBLE) this.gone() else this.visible()
fun View.visible() {
visibility = View.VISIBLE
}
fun View.gone() {
visibility = View.GONE
}
/**
* Remember to add this permission to the Manifest:
* <uses-permission android:name="android.permission.VIBRATE"/>
*/
inline fun View.consumeButtonWithHapticFeedback(lambda: () -> Unit) {
lambda()
this.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
}
// Menu
fun Menu.toggleIconForAction(actionId: Int) = this.findItem(actionid).setIcon(if (conditionTrue) R.drawable.ic_enabled else R.drawable.ic_disabled)
// View Group
fun ViewGroup.inflate(layoutRes: Int): View = LayoutInflater.from(context).inflate(layoutRes, this, false)
// Bottom sheet dialog
inline fun BottomSheetDialog.consumeBottomSheetDialog(lambda: () -> Unit) {
this.dismiss()
lambda()
}
// Text Input Edit Text
fun TextInputEditText.setTextWithBlankStringCheck(string: String) = if (string.isNotBlank()) this.setText(string) else null
// RecyclerView
fun <T : RecyclerView.ViewHolder> T.onClick(flatPosition: Int? = null, event: (view: View, position: Int, type: Int) -> Unit): T {
this.itemView.setOnClickListener { event.invoke(it, flatPosition ?: this@onClick.adapterPosition, this@onClick.itemViewType) }
return this
}
fun <T : RecyclerView.ViewHolder> T.onLongClick(event: (view: View, position: Int, type: Int) -> Unit): T {
itemView.setOnLongClickListener {
event.invoke(it, adapterPosition, itemViewType)
true
}
return this
}
/**
* CONTEXT
*/
// CLipboard
fun Context.clipboard(): ClipboardManager = this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
fun Context.clearClipboard() = apply { clipboard().primaryClip = ClipData.newPlainText("", "") }
fun Context.hasItemInClipboard(): Boolean = clipboard().primaryClip != null
fun Context.getItemFromClipboard(): String? {
val clipboard = clipboard()
return if (clipboard.primaryClip != null) clipboard.primaryClip.getItemAt(0).text.toString() else null
}
fun Context.saveItemToClipboard(string: String) = apply { clipboard().primaryClip = ClipData.newPlainText("sample_item_id", string) }
fun Context.openPlayStore() {
try {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName)))
} catch (anfe: ActivityNotFoundException) {
startActivity(
Intent(
Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)
)
)
}
}
/**
* STRING
*/
// URLs
fun String.hasProtocol() = this.indexOf("http") != -1
fun String.cleanFromSpaces() = this.replace("\\s+".toRegex(), "")
fun String.substringAtProtocol() = this.substring(indexOf("http")).cleanFromSpaces()
fun String.addProtocol() = "http://" + this.cleanFromSpaces()
fun String.polished() = if (this.hasProtocol()) this.substringAtProtocol() else this.addProtocol()
/**
* RETROFIT
*/
fun ResponseBody.toJsoupDocument(): Document = Jsoup.parse(this.byteStream(), "UTF-8", "")
/**
* PICASSO
*/
fun ImageView.loadImageFromWeb(url: String) {
try {
Picasso.with(context)
.load(url)
.placeholder(R.drawable.ic_placeholder)
.into(ivSample)
} catch (e: Exception) {
println("ERROR in PICASSO - $e")
}
}
/**
* FIREBASE & ADMOB
*/
fun Context.sendFirebaseEvent(contentType: FirebaseContentType, action: FirebaseAction) {
val bundle = Bundle()
with(bundle) {
putString(FirebaseAnalytics.Param.CONTENT_TYPE, contentType.description)
putString(FirebaseAnalytics.Param.ITEM_ID, action.description)
}
FirebaseAnalytics.getInstance(this).logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle)
}
fun Context.getAdString(): String = this.resources.getString(if (Utils.isAdsDebugActive()) R.string.testMobileVideoAds else R.string.mobileVideoAds)
object Utils {
// date time
const val dateTimeFormatISO8601 = "yyyy-MM-dd HH:mm:ss"
// url
fun getHostOfURL(url: String): String = URL(url).host
// OS versions
fun ifAtLeast(version: Int, f: () -> Unit) {
if (android.os.Build.VERSION.SDK_INT >= version) f()
}
fun atLeast(version: Int): Boolean = android.os.Build.VERSION.SDK_INT >= version
// debug
fun isAdsDebugActive(): Boolean = if (!BuildConfig.DEBUG) BuildConfig.DEBUG else true
}
enum class FirebaseContentType(val description: String) {
SAMPLE_INTERACTION("sample_interaction")
}
enum class FirebaseAction(val description: String) {
SAMPLE_ACTION("sample_action")
}
@harryhan24
Copy link
Copy Markdown

this gist really helpful for me. thx !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment