I looked at all of the other questions about this error, but none of them helped. I am trying to create a reference to a button in my layout file, and when I set the onClickListener, I get "expecting member declaration." This occurs on line 35. Side note, I am also getting the error "Function declaration must have a name" on the same line. Here is the code:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
private var userLocation: Any = ""
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val spinner: Spinner = findViewById<Spinner>(R.id.locations)
spinner.adapter = ArrayAdapter(
this,
android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item,
resources.getStringArray(R.array.rooms)
)
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
adapterView: AdapterView<*>?,
view: View?,
position: Int,
p3: Long
) {
userLocation = adapterView?.getItemAtPosition(position)!!
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
}
val button: Button = findViewById<Button>(R.id.button)
button.setOnClickListener{
Toast.makeText(this, "Selected $userLocation", Toast.LENGTH_SHORT).show()
}
}
CodePudding user response:
These lines of code:
val button: Button = findViewById<Button>(R.id.button)
button.setOnClickListener{
Toast.makeText(this, "Selected $userLocation", Toast.LENGTH_SHORT).show()
}
you have defined outside any functions. That means button
is a class-level property you are defining. Properties are initialized before any functions are called, so this findViewById
call will fail at runtime because it will be called before onCreate()
.
And you cannot simply call a function like setOnClickListener
at the the top level of a function in the middle of nowhere. That's why you have the "expecting member declaration" error.
You need to move all of this code inside your onCreate()
function.