• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

mcxiaoke/kotlin-koi: Koi, a lightweight kotlin library for Android Development.

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

mcxiaoke/kotlin-koi

开源软件地址(OpenSource Url):

https://github.com/mcxiaoke/kotlin-koi

开源编程语言(OpenSource Language):

Kotlin 99.4%

开源软件介绍(OpenSource Introduction):

Koi - A lightweight Kotlin library for Android

Koi include many useful extensions and functions, they can help reducing the boilerplate code in Android applications. Specifically, Koi include a powerful extension function named asyncSafe.

Gradle

Latest Version: Maven Central Compiled with Kotlin 1.1.4.

compile 'com.mcxiaoke.koi:core:0.5.5' // useful extensions (only ~100k)
compile 'com.mcxiaoke.koi:async:0.5.5' // async functions (only ~70k)

Usage

Context Extensions

Activity Functions

// available for Activity
fun activityExtensions() {
    val act = getActivity() // Activity
    act.restart() // restart Activity
    val app = act.getApp() // Application
    val app2 = act.application  // Application
    // Activity.find()
    // Fragment.find()
    // View.find()
    val textView = act.find<TextView>(android.R.id.text1)
}

Fragment Functions

// available for Fragment
fun fragmentExtensions() {
    val act = activity // Activity
    val app = getApp() // Application
    val textView = find<TextView>(android.R.id.text1) // view.findViewById
    val imageView = find<TextView>(android.R.id.icon1) // view.findViewById
    }

Easy to use Toast

// available for Context
fun toastExtensions() {
    // available in Activity/Fragment/Service/Context
    toast(R.string.app_name)
    toast("this is a toast")
    longToast(R.string.app_name)
    longToast("this is a long toast")
}

Easy to Inflate Layout

    // available for Context
    fun inflateLayout() {
        val view1 = inflate(R.layout.activity_main)
        val viewGroup = view1 as ViewGroup
        val view2 = inflate(android.R.layout.activity_list_item, viewGroup, false)
    }

Useful Functions

// available for Context
fun miscExtensions() {
    val hasCamera = hasCamera()

    mediaScan(Uri.parse("file:///sdcard/Pictures/koi/cat.png"))
    addToMediaStore(File("/sdcard/Pictures/koi/cat.png"))

    val batteryStatusIntent = getBatteryStatus()
    val colorValue = getResourceValue(android.R.color.darker_gray)
}

Easy to create Intent

// available for Context
fun intentExtensions() {
    val extras = Bundle { putString("key", "value") }
    val intent1 = newIntent<MainActivity>()
    val intent2 = newIntent<MainActivity>(Intent.FLAG_ACTIVITY_NEW_TASK, extras)
}

Easy to Start Activity

// available for Activity
fun startActivityExtensions() {
    startActivity<MainActivity>()
    // equal to
    startActivity(Intent(this, MainActivity::class.java))

    startActivity<MainActivity>(Intent.FLAG_ACTIVITY_SINGLE_TOP, Bundle())
    startActivity<MainActivity>(Bundle())

    startActivityForResult<MainActivity>(100)
    startActivityForResult<MainActivity>(Bundle(), 100)
    startActivityForResult<MainActivity>(200, Intent.FLAG_ACTIVITY_CLEAR_TOP)
}

Easy to Start Service

// available for Context
fun startServiceExtensions() {
    startService<BackgroundService>()
    startService<BackgroundService>(Bundle())
}

Network State

// available for Context
fun networkExtensions() {
    val name = networkTypeName()
    val operator = networkOperator()
    val type = networkType()
    val wifi = isWifi()
    val mobile = isMobile()
    val connected = isConnected()
}

Notification Builder

// available for Context
fun notificationExtensions() {
    // easy way using Notification.Builder
    val notification = newNotification() {
        this.setColor(0x0099cc)
                .setAutoCancel(true)
                .setContentTitle("Notification Title")
                .setContentText("Notification Message Text")
                .setDefaults(0)
                .setGroup("koi")
                .setVibrate(longArrayOf(1, 0, 0, 1))
                .setSubText("this is a sub title")
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setLargeIcon(null)
    }
}

Package Functions

// available for Context
fun packageExtensions() {
    val isYoutubeInstalled = isAppInstalled("com.google.android.youtube")
    val isMainProcess = isMainProcess()
    val disabled = isComponentDisabled(MainActivity::class.java)
    enableComponent(MainActivity::class.java)

    val sig = getPackageSignature()
    val sigString = getSignature()
    println(dumpSignature())
}

System Service

// available for Context
// easy way to get system service, no cast
fun systemServices() {
    val wm = getWindowService()
    val tm = getTelephonyManager()
    val nm = getNotificationManager()
    val cm = getConnectivityManager()
    val am = getAccountManager()
    val acm = getActivityManager()
    val alm = getAlarmManager()
    val imm = getInputMethodManager()
    val inflater = getLayoutService()
    val lm = getLocationManager()
    val wifi = getWifiManager()
}

Easy to Log

// available for Context
fun logExtensions() {
    KoiConfig.logEnabled = true //default is false
    // true == Log.VERBOSE
    // false == Log.ASSERT
    // optional
    KoiConfig.logLevel = Log.VERBOSE // default is Log.ASSERT
    //

    logv("log functions available in Context")  //Log.v
    logd("log functions available in Context")  //Log.d
    loge("log functions available in Context")   //Log.e

    // support lazy evaluated message
    logv { "lazy eval message lambda" }  //Log.v
    logw { "lazy eval message lambda" }  //Log.w
}

View Extensions

View Listeners 1

fun viewListeners1() {
    val view = View(this)
    // View.OnClickListener
    view.onClick { print("view clicked") }
    // View.OnLongClickListener
    view.onLongClick { print("view long clicked");false }
    // View.OnKeyListener
    view.onKeyEvent { view, keyCode, event ->
        print("keyEvent: action:${event.action} code:$keyCode")
        false
    }
    // View.OnTouchListener
    view.onTouchEvent { view, event ->
        when (event.actionMasked) {
            MotionEvent.ACTION_DOWN -> print("touch down")
            MotionEvent.ACTION_UP -> print("touch up")
            MotionEvent.ACTION_MOVE -> print("touch move")
        }
        false
    }
    // View.OnFocusChangeListener
    view.onFocusChange { view, hasFocus ->
        print("focus changed = $hasFocus")
    }
}

View Listeners 2

fun viewListeners2() {
    // TextWatcher
    val editText = EditText(this)
    editText.onTextChange { text, start, before, count ->
        print("text changed: $text")
    }

    // OnCheckedChangeListener
    val checkBox = CheckBox(this)
    checkBox.onCheckedChanged { button, isChecked ->
        print("CheckBox value changed:$isChecked")
    }

    // OnSeekBarChangeListener
    val seekBar = SeekBar(this)
    seekBar.onProgressChanged { seekBar, progress, fromUser ->
        print("seekBar progress: $progress")
    }
}

ListView Listeners

fun listViewListeners() {
    val listView = ListView(this)
    // OnItemClickListener
    listView.onItemClick { parent, view, position, id ->
        print("onItemClick: position=$position")
    }
    // OnScrollListener
    listView.onScrollChanged { view, scrollState ->
        print("scroll state changed")
    }
}

View Utils

// available for View
fun viewSample() {
    val w = dm.widthPixels
    val h = dm.heightPixels
    val v1 = 32.5f
    val dp1 = v1.pxToDp()
    val v2 = 24f
    val px1 = v2.dpToPx()
    val dp2 = pxToDp(56)
    val px2 = dpToPx(32)
    val dp3 = 72.pxToDp()
    val px3 = 48.dpToPx()

    hideSoftKeyboard()
    val editText = EditText(context)
    editText.showSoftKeyboard()
    editText.toggleSoftKeyboard()
}

Adapter Extensions

Easy to Create Adapter

// easy way to create array adapter
fun adapterFunctions() {
    listView.adapter = quickAdapterOf(
            android.R.layout.simple_list_item_2,
            (1..100).map { "List Item No.$it" })
    { binder, data ->
        binder.setText(android.R.id.text1, data)
        binder.setText(android.R.id.text2, "Index: ${binder.position}")
    }

    val adapter2 = quickAdapterOf<String>(android.R.layout.simple_list_item_1) {
        binder, data ->
        binder.setText(android.R.id.text1, data)
    }
    adapter2.addAll(listOf("Cat", "Dog", "Rabbit"))

    val adapter3 = quickAdapterOf<Int>(android.R.layout.simple_list_item_1,
            arrayOf(1, 2, 3, 4, 5, 6)) {
        binder, data ->
        binder.setText(android.R.id.text1, "Item Number: $data")
    }

    val adapter4 = quickAdapterOf<Int>(android.R.layout.simple_list_item_1,
            setOf(22, 33, 4, 5, 6, 8, 8, 8)) {
        binder, data ->
        binder.setText(android.R.id.text1, "Item Number: $data")
    }
}

Bundle Extensions

Bundle Builder

// available in any where
fun bundleExtension() {
    // easy way to create bundle
    val bundle = Bundle {
        putString("key", "value")
        putInt("int", 12345)
        putBoolean("boolean", false)
        putIntArray("intArray", intArrayOf(1, 2, 3, 4, 5))
        putStringArrayList("strings", arrayListOf("Hello", "World", "Cat"))
    }

    // equal to using with
    val bundle2 = Bundle()
    with(bundle2) {
        putString("key", "value")
        putInt("int", 12345)
        putBoolean("boolean", false)
        putIntArray("intArray", intArrayOf(1, 2, 3, 4, 5))
        putStringArrayList("strings", arrayListOf("Hello", "World", "Cat"))
    }
}

Parcelable Extensions

Easy to create Parcelable

// easy way to create Android Parcelable class
data class Person(val name: String, val age: Int) : Parcelable {
    override fun writeToParcel(dest: Parcel, flags: Int) {
        dest.writeString(name)
        dest.writeInt(age)
    }

    override fun describeContents(): Int = 0
    protected constructor(p: Parcel) : this(name = p.readString(), age = p.readInt()) {}
    companion object {
        // using createParcel
        @JvmField val CREATOR = createParcel { Person(it) }
    }
}

Collection Extensions

Collection to String


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap