Code前端首页关于Code前端联系我们

Kotlin有效开发Android App(一)

terry 2年前 (2023-09-22) 阅读数 72 #移动小程序

做区块链相关钱包项目。新应用程序使用了新技术堆栈。我们在Android中使用Kotlin+RxJava+Android架构组件,在iOS中使用Swift+RxSwift。本文不讨论应用程序的架构,仅讨论项目中使用的 Kotlin 的功能。

在Android应用程序中,毫不夸张地说,我们95%以上的代码都是Kotlin开发的。因此,现阶段有必要对Kotlin的用途做一个简单的总结。

Kotlin使用的功能:

1。

Kotlin 扩展功能允许开发人员向类添加新功能,而无需更改现有类。该函数称为扩展函数。

举个简单的例子。如果要关闭 I/O 流,可以使用 Java 编写处理程序方法。

    /**
     * 安全关闭io流
     * @param closeable
     */
    public static void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
复制代码

对于 Kotlin,可以使用 closeQuietly() 函数扩展 Closeable。

fun Closeable?.closeQuietly() {
    try {
        this?.close()
    } catch (e: Throwable) {
    }
}
复制代码

然后任何实现 Closeable 接口的类都可以使用自己的 closeQuietly() 方法来关闭流。我们不再需要这个工具方法了。

在项目中,我们使用了扩展函数来封装Glide,大大简化了Glide的使用。

/**
 * 占位符矩形
 */
fun ImageView.load(url: String) {
    get(url).placeholder(R.drawable.shape_default_rec_bg)
            .error(R.drawable.shape_default_rec_bg)
            .into(this)
}

/**
 * 占位符圆角矩形
 */
fun ImageView.loadRound(url: String) {
    get(url).placeholder(R.drawable.shape_default_round_bg)
            .error(R.drawable.shape_default_round_bg)
//            .apply(RequestOptions.bitmapTransform(RoundedCornersTransformation(DisplayUtil.dp2px(context, 6f), 0)))
            .transform(RoundedCornersTransformation(DisplayUtil.dp2px(context, 6f), 0))
            .into(this)
}

/**
 * 占位符圆形
 */
fun ImageView.loadCircle(url: Drawable) {
    get(url).placeholder(R.drawable.shape_default_circle_bg)
            .error(R.drawable.shape_default_circle_bg)
            .into(this)
}

fun ImageView.loadCircle(url: String) {
    get(url).placeholder(R.drawable.shape_default_circle_bg)
            .error(R.drawable.shape_default_circle_bg)
            .into(this)
}

fun ImageView.get(url: String): GlideRequest<Drawable> = GlideApp.with(context).load(url)
fun ImageView.get(url: Drawable): GlideRequest<Drawable> = GlideApp.with(context).load(url)
复制代码

此外,我们还在很多地方使用了扩展功能。

顺便更新了我的Kolin工具库,里面有各种工具和各种扩展 https://github.com/fengzhizi715/SAF-Kotlin-Utils

2.路由闭合

我没看懂一开始就是这个概念。有时我看到我们的小伙伴在使用RxBus的时候写了这样的代码:

RxBus.get().register(LogoutEvent::class.java) { refresh() }
复制代码

我当时就觉得很困惑,因为我写了RxBus,我记得没有这样的方法。点击register()方法后,发现寄存器是这样的:

    public <T> Disposable register(Class<T> eventType, Consumer<T> onNext) {
        return toObservable(eventType).observeOn(AndroidSchedulers.mainThread()).subscribe(onNext);
    }
复制代码

使用Kotlin,register方法的使用可以简化为这样:

RxBus.get().register(LogoutEvent::class.java,{
            refresh()
        })
复制代码

从register()的最后一个参数来看,是一个方法或闭包可以将方法或闭包带到外部。它就变成了你在项目中看到的样子:

RxBus.get().register(LogoutEvent::class.java) { refresh() }
复制代码

这是一个尾随闭包,会让代码看起来更简洁。

3。使用 with

With 是使用对象作为函数参数。可以在功能块中引用该对象。您可以直接调用功能块内对象的方法或属性。

/**
 * Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
 */
@kotlin.internal.InlineOnly
public inline fun <T, R> with(receiver: T, block: T.() -> R): R {
    contract {
        callsInPlace(block, InvocationKind.EXACTLY_ONCE)
    }
    return receiver.block()
}
复制代码

使用适配器后使用 s 之前

class AppPublisherAdapter : BaseAdapter<BoundAppInfoResponse.AppInfo>() {

    override fun getLayoutId(viewType: Int): Int = R.layout.cell_app_publisher

    override fun onBindViewHolderImpl(holder: BaseViewHolder, position: Int,content: BoundAppInfoResponse.AppInfo) {
        holder.itemView.tv_game_name.text = content.name

        if (content.is_bound) {
            holder.itemView.tv_bound_user_name.text = content.bound_user_name
            holder.itemView.tv_bound_user_name.setTextColor(context.resources.getColor(R.color.color_bound_user_name))
        } else {
            holder.itemView.tv_bound_user_name.text = context.getString(R.string.bind_on_account)
            holder.itemView.tv_bound_user_name.setTextColor(context.resources.getColor(R.color.color_bind_on_account))
        }
        holder.itemView.iv_game_icon.load(content.logo_url)
    }
}
复制代码

使用 s 后,功能块可能会省略“内容”。

class AppPublisherAdapter : BaseAdapter<BoundAppInfoResponse.AppInfo>() {

    override fun getLayoutId(viewType: Int): Int = R.layout.cell_app_publisher

    override fun onBindViewHolderImpl(holder: BaseViewHolder, position: Int, content: BoundAppInfoResponse.AppInfo) {

        with(content) {
            holder.itemView.tv_game_name.text = name

            if (is_bound) {
                holder.itemView.tv_bound_user_name.text = bound_user_name
                holder.itemView.tv_bound_user_name.setTextColor(context.color(R.color.color_bound_user_name))
            } else {
                holder.itemView.tv_bound_user_name.text = context.string(R.string.bind_on_account)
                holder.itemView.tv_bound_user_name.setTextColor(context.color(R.color.color_bind_on_account))
            }
            holder.itemView.iv_game_icon.load(logo_url)
        }
    }
}
复制代码

4。其他

这部分内容不是Kotlin的表征,是我对Kotlin开发的工具的使用。比如日志框架L和Retrofit日志拦截器。这些库实际上开发得很早,并且最近它们的功能略有更新。

L github地址:https://github.com/fengzhizi715/SAF-Kotlin-log

重构日志拦截器github地址:https://github.com/fengzhizi715/safnder-logging拦截器♽日志拦截器:Kotlin高效地开发Android App(一)

总结

Kotlin吸收了多种语言的优点,相比Java有很多有趣的特性,大大提高了开发效率。本文描述的功能只是九牛一毛。接下来,我将编译项目中使用的其他 Kotlin 函数。

作者:Tony沈哲
链接:https://juejin.im/post/5ade9ce3f265da0b80705e22
来源:掘金
。商业转载请联系作者获得许可。非商业转载请注明来源。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门