要这么写:
package com.example.avtivitytest
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.avtivitytest.databinding.FirstLayoutBinding
class FirstActivity : AppCompatActivity() {
private lateinit var firstActivityBinding: FirstLayoutBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
firstActivityBinding = FirstLayoutBinding.inflate(layoutInflater)
setContentView(firstActivityBinding.root)
initView()
setHasOptionsMenu(true)
}
private fun setHasOptionsMenu(b: Boolean) {
}
private fun initView() {
firstActivityBinding.button1.setOnClickListener {
Toast.makeText(this,"cliked The button 1",Toast.LENGTH_SHORT).show()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId){
R.id.add_item -> Toast.makeText(this,"You clicked Add",
Toast.LENGTH_SHORT).show()
R.id.remove_item -> Toast.makeText(this,"You clicked Remove",
Toast.LENGTH_SHORT).show()
}
return true
}
}