Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method from Kotlin class

I have an util Kotlin class where I set toolbar title, hide or show toolbar depends on the fragment:

class MyToolbarUtils() {

    fun hideToolbar(activity: Activity) {
        (activity as MainActivity).supportActionBar!!.hide()
    }

    fun showToolbar(activity: Activity, tag: String) {
        setToolbarTitle(tag, activity)
        (activity as MainActivity).supportActionBar!!.show()
    }

    fun setToolbarTitle(tag: String, activity: Activity) {
        var title = ""
        when (tag) {
            "Main_fragment" -> title = activity.resources.getString(R.string.Main_screen)
            "Add_note" -> title = activity.resources.getString(R.string.Add_note)
        }
        activity.title = title
    }
}

how to call showToolbar(...) from Fragment? I just tried MyToolbarUtils.showToolbar(..) but it can not be possible

only one way I discover is:

val setToolbarTitle = MyToolbarUtils()
setToolbarTitle.showToolbar(activity, tag)

but there must be better way to do that..

like image 244
Stepan Avatar asked Sep 14 '16 11:09

Stepan


People also ask

How do I call a method in Kotlin?

Before you can use (call) a function, you need to define it. To define a function in Kotlin, fun keyword is used. Then comes the name of the function (identifier). Here, the name of the function is callMe .

What is Vararg in Kotlin?

In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.

What does :: means in Kotlin?

:: is just a way to write a lambda expression basically we can use this to refer to a method i.e a member function or property for example class Person (val name: String, val age: Int) Now we can write this to access the person which has the maximium age.


1 Answers

Convert your class into an object which is supposed to work similarly to java static methods.

You can get more info here: https://kotlinlang.org/docs/reference/object-declarations.html#object-declarations

like image 149
ilya.dorofeev Avatar answered Sep 30 '22 13:09

ilya.dorofeev