/**
* Created on 2017/5/29.
* Extend.kt
*/
class Extend
/**
* setWindow window的一些设置
* Activity 的扩展函数
* @param fullScreen 默认为 false. true: 全屏
* @param actionBar 默认为 true. true: 显示ActionBar
* @param orientation 默认为 0: AUTO. 1: PORTRAIT 2: LANDSCAPE
* 在setContentView()之前调用
*/
fun Activity.setWindow(fullScreen: Boolean = false, actionBar: Boolean = true, orientation: Int = 0) {
if (fullScreen)
window.setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN)
if (!actionBar)
requestWindowFeature(Window.FEATURE_NO_TITLE)
when (orientation) {
1 -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
2 -> requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}
}
/**
* gotoActivity Activity跳转
* Activity 的扩展函数
* @param finish 默认为 true. true: 销毁this; false: 保留this,可以返回
* @param activity 解释=掩饰
* inline reified
*/
inline fun <reified activity : Activity> Activity.gotoActivity(finish: Boolean = true) {
startActivity(Intent(this, activity::class.java))
if (finish) finish()
}
/**
* toast: Toast 的简化版
* Activity 的扩展函数
* @param msg Message
* @param isLong 默认值为 false. true: LONG; false: SHORT
*/
fun Activity.toast(msg: String, isLong: Boolean = false) {
if (isLong)
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}
/**
* log: Log 的简化版
* Activity 的扩展函数
* @param msg Message
* @param tag 默认值为 "AUTO"
*/
fun Activity.log(msg: String, tag: String = "AUTO") {
Log.i(tag, msg)
}
/**
* toIntWithDefault 如果 String 转换出错,就用默认值代替
* String 的扩展函数
* @param def 默认值
* @return Int
*/
fun String.toIntWithDefault(def: Int): Int{
var i: Int
try {
i = this.toInt()
} catch (e: NumberFormatException) {
i = def
}
return i
}
/**
* log: 双击返回键退出
* Activity 的扩展函数
* @param b 从外部定义的一个变量(初始为false)
* @param msg Message("再按一次退出游戏")
* @param keyCode onKeyDown中得到的参数
* @return Boolean 再次传到b中
* Eg: b = exitByDClick(b, keycode, "再按一次退出游戏")
* PS: 接收用的变量和第一个参数是同一个变量。
*/
fun Activity.exitByDClick(b:Boolean, keyCode: Int, msg: String):Boolean{
var isExit = b
if (keyCode == KeyEvent.KEYCODE_BACK) {
val handler = Handler()
if ((!isExit)) {
isExit = true
toast(msg)
handler.postDelayed({ isExit = false }, 1000 * 2) //x秒后没按就取消
} else {
finish()
System.exit(0)
}
}
return isExit
}