如何访问 Android 库 kotlin 函数

how to access Android library kotlin functions

我在我的 Android 库中编写了一个简单的函数,我想在我的 Android 项目中使用它。我无法从 android 项目访问该库函数。

导入没问题,我可以从项目中获取 Util class。只是我无法访问 kotlin 函数

注意:Android 库在 Android 项目中

我得到Unresolved reference: specialToast

Android 库函数

class Util {

    fun specialToast(context: Context, string: String) {
        Toast.makeText(context, string, Toast.LENGTH_LONG).show()
    }
}

Android 项目

import com.i6systems.offlineservicelibrary.Util

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Util.specialToast(applicationContext, "test")
        //****Unresolved reference: specialToast*****
    }
}

感谢您的建议

R

I created a companion object and placed the function in it and that worked. but what is the right way?

惯用的 Kotlin 方式是

The recommended practice is to never use object for creating namespaces, and to always use top-level declarations when possible. We haven’t found name conflicts to be an issue, and if you do get a conflict, you can resolve it using an import with alias.

所以

// outside any class or object
fun specialToast(context: Context, string: String) {
    Toast.makeText(context, string, Toast.LENGTH_LONG).show()
}

在一个文件中并且

import com.i6systems.offlineservicelibrary.specialToast

...
specialToast(applicationContext, "test")

在另一个。