将Anko应用到项目中

Anko是JetBrains开发的Android库,它简化了代码并提高了开发效率。Anko Commons提供了方便的扩展函数,如上下文的showToast方法和dp转换功能。此外,还介绍了Anko的扩展属性特性,允许在不修改原有类的情况下增加功能,例如Track模型的isNeedVip属性。尽管不能直接用于Gson解析,但在某些场景下,扩展属性能有效增强代码的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Anko是JetBrains开发的一个强大的库。让android开发更加快速和容易。它可以简化你的代码,使其易读。
Anko包含几个部分:

  • Anko Commons:一个轻量的工具包,用来操作intent,dialog,log等等
  • Anko Layouts:一种快速安全的方法,用来动态生成布局
  • Anko SQLite:


这里只对Anko Commons进行介绍。

1、扩展

1.1
扩展函数是指在一个类上增加一个新的行为,甚至我们不需要获得这个类的权限。
举个例子,我们平时用的showToast方法。在java的写法如下:


public static void showToast(Context context, int message, int duration) {
    Toast.makeText(context, message, duration).show();
}


在Kotlin的写法如下:
fun Context.showToast(message: String, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, duration).show()
}


如果是java的写法,那么调用的方式一般是XXX.showToast(context, message, duration)。如果是Kotlin,那么这个方法于所有Context的子类都可以去调用。简便性,显而易见。


fun Int.dp(context: Context): Int {
   if (context == null)
       return (this 1.5).toInt()
   val scale = context.resources.displayMetrics.density
   return (this * scale + 0.5).toInt()
}
dp在java代码中的使用,可以这么写10.dp(context).
以上只是一个简单的例子,Anko将这个优势发挥极致,提供了很多很好用的方法在Anko Commons中。


1.2
扩展属性更是牛逼啊。。。
我们可以随便点开一个我们的业务model,如Track多的有十几二十个属性,而其实很多都是并不通用,可能我就这个页面用到,所以给他新增进去,一来一往,就有很多了。今天借助Kotlin,我们将有怎么样的效果。比如我这个会员页,希望知道声音是否是会员属性
val Track.isNeedVip: Boolean
   get() = isPaid && !UserInfoMannage.getInstance().user.isVip()
这样子,根本不需要往Track里面去塞新的字段,就能实现我们要的功能。虽然无法参与Gson解析,但是通过手动解析完全没有任何问题。(但也不一定,setter方法可能可以处理下,我还没试过)


1.3难点
Extensions declared as members can be declared as open and overridden in subclasses. This means that the dispatch of such functions is virtual with regard to the dispatch receiver type, but static with regard to the extension receiver type.

openclass D {
}
class D1 : D() {
}
openclass C {
    openfun D.foo() {
        println("D.foo in C")
    }
    openfun D1.foo() {
        println("D1.foo in C")
    }
    fun caller(d: D) {
        d.foo() // call the extension function
    }
}
class C1 : C() {
    overridefun D.foo() {
        println("D.foo in C1")
    }
    overridefun D1.foo() {
        println("D1.foo in C1")
    }
}
C().caller(D())// prints "D.foo in C"
C1().caller(D())// prints "D.foo in C1" - dispatch receiver is resolved virtually
C().caller(D1())// prints "D.foo in C" - extension receiver is resolved statically


2、Anko Commons

a.操作Intent
startActivity(intentFor<SomeOtherActivity>("id" to 5).singleTop())
startActivity<SomeOtherActivity>("id" to 5)
browse(url)

b.使用Dialog

        toast("你好")
        
        alert("Warining", "Are U sure?") {
            yesButton { toast("Ok…") }
            noButton {}
        }.show()
        
        val countries = listOf("China", "USA", "UK", "Australia")
        selector("Where are you from?", countries) { i ->
            toast("So you're living in ${countries[i]}, right?")
        }
        
        val dialog = progressDialog(message = "Please wait a bit…", title = "Fetching data")

c. 打log
使用AnkoLogger可以很方便的打log。
class SomeActivity : Activity() {
    private val log = AnkoLogger<SomeActivity>(this)
    private val logWithASpecificTag = AnkoLogger("my_tag")
    private fun someMethod() {
        log.warning("Big brother is watching you!")
    }
}

class SomeActivity : Activity(), AnkoLogger {
    private fun someMethod() {
        info("London is the capital of Great Britain")
        debug(5) // .toString() method will be executed
        warn(null) // "null" will be printed
    }
}

//d.资源处理
//Dimensions
//dip(dipValue)
//sp(spValue)
//px2dip
//px2sp

fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()
//Colors
//0xff0000.opaque将16进制值转换成color的int类型
//    ApplyRecursively
    View.applyRecursively { view -> when(view) {
        is EditText -> view.textSize = 20f
    }}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值