I'm a beginner of Kotlin, the following code is from a webpage, I can't understand that the parameter this@MainActivity
in the code layoutManager = LinearLayoutManager(this@MainActivity)
, Could you tell me? Thanks!
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.Menu
import android.view.MenuItem
import kotlinx.android.synthetic.main.activity_main.*
import mobi.porquenao.poc.kotlin.R
class MainActivity : BaseActivity() {
lateinit var listAdapter: MainAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
with (list) {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@MainActivity)
listAdapter = MainAdapter()
adapter = listAdapter
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
listAdapter.add()
list.smoothScrollToPosition(0)
return true
}
}
It is a qualified this
, used to access MainActivity
's context from an outer scope.
class MainActivity {
fun onCreate() {
val list = listOf(1, 2, 3)
with (list) {
println(this) // >>> [1, 2, 3]
println(this@MainActivity) // >>> MainActivity@2a84aee7
}
}
}
You can read more about this approach in Kotlin documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With