Last active
May 21, 2019 09:37
-
-
Save hwd6190128/d65d3ec12e50f1f02dc56cb963439781 to your computer and use it in GitHub Desktop.
Utils fun of android dev
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val Int.pxToDp: Int | |
get() = (this / Resources.getSystem().displayMetrics.density).toInt() | |
val Int.dpToPx: Int | |
get() = (this * Resources.getSystem().displayMetrics.density).toInt() | |
val Int.spToPx: Int | |
get() = (this * Resources.getSystem().displayMetrics.scaledDensity).toInt() | |
/** | |
* Get coclor string & set style | |
*/ | |
fun getSpannableString(text: String, color: Int, style: StyleSpan = StyleSpan(Typeface.NORMAL)): SpannableString { | |
val span = SpannableString(text) | |
span.setSpan(ForegroundColorSpan(color), 0, text.length, 0)// set color | |
span.setSpan(style, 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) | |
return span | |
} | |
/** | |
* Get coclor string, set style & resize | |
*/ | |
fun getSizeSpannableString( | |
text: String, | |
sizeSpan: Int, | |
color: Int, | |
style: StyleSpan = StyleSpan(Typeface.NORMAL) | |
): SpannableString { | |
val span = SpannableString(text) | |
span.setSpan(AbsoluteSizeSpan(sizeSpan), 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) | |
span.setSpan(ForegroundColorSpan(color), 0, text.length, 0)// set color | |
span.setSpan(style, 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) | |
return span | |
} | |
/** | |
* Format string to locale number | |
* ***,***,*** | |
*/ | |
fun decimalFormat(str: String): String { | |
return try { | |
val nf = NumberFormat.getCurrencyInstance(Locale.US) | |
val pattern = (nf as DecimalFormat).toPattern() | |
val newPattern = pattern.replace("\u00A4", "").trim() | |
val newFormat = DecimalFormat(newPattern) | |
newFormat.format(moneyStr.toDouble()) | |
} catch (e: Exception) { | |
Log.w("decimalFormat", "[moneyFormat] exception: %s", e.message) | |
moneyStr | |
} | |
} | |
fun isAppOnForeground(context: Context?): Boolean { | |
if (context == null) { | |
return false | |
} | |
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager | |
val appProcesses = activityManager.runningAppProcesses ?: return false | |
val packageName = context.packageName | |
for (appProcess in appProcesses) { | |
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND | |
&& appProcess.processName == packageName) { | |
return true | |
} | |
} | |
return false | |
} | |
fun isActivityRunning(ctx: Activity?): Boolean { | |
return ctx != null && ctx.window != null && ctx.window.decorView.rootView.isShown | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment