简体   繁体   中英

How can i create a function outside of the MainActivity Kotlin

I have a function:

fun showDialogWindow(){
val builder = AlertDialog.Builder(this)
val inflater = layoutInflater
val dialogLayout = inflater.inflate(R.layout.dialog_window, null)
val editText = dialogLayout.findViewById<EditText>(R.id.change_balance_edittext)

with(builder) {
    setPositiveButton("Ok"){dialog, which ->
        Values.balance = editText.text.toString().toFloat()
    }
    setNegativeButton("Cancel"){dialog, which ->
    }
    setView(dialogLayout)
    show()
}
}

I want to create it in separate file, when i try to do it, i have some mistakes: in 2 line 'this' is not defined in this context ,in 3 Unresolved reference: layoutInflater and in 13 Overload resolution ambiguity . In MainActivity fun is working. How can i solve it?

First I would try to look at how the language works and where you can call variables.

Per example, the "this" error is because when you are calling "this" in the MainActivity, it gets the activity type, probably "AppCompatActivity". When calling in a new file, you need to pass the value "this" as a parameter in the funtion.

fun showDialogWindow(mainActivity : Context){
val builder = AlertDialog.Builder(mainActivity )
val inflater = layoutInflater
val dialogLayout = inflater.inflate(R.layout.dialog_window, null)
val editText = dialogLayout.findViewById<EditText>(R.id.change_balance_edittext)

    with(builder) {
        setPositiveButton("Ok"){dialog, which ->
            Values.balance = editText.text.toString().toFloat()
    }
    setNegativeButton("Cancel"){dialog, which ->
    }
    setView(dialogLayout)
    show()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM