我是kotlin的新手,我需要在操作栏中添加操作按钮。我在文件夹res / menu中创建了这个menuTest.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_fav"
android:icon="@drawable/ic_action_edit"
app:showAsAction="ifRoom"
android:title="@string/edit" />
</menu>
这是我的layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="DetailItem">
<ImageView
android:id="@+id/itemIdImage"
android:layout_width="358dp"
android:layout_height="214dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:padding="10dp"
app:srcCompat="@drawable/logo"
tools:layout_editor_absoluteX="13dp"
tools:layout_editor_absoluteY="16dp" />
</RelativeLayout>
我的Activity.kt
class DetailCar : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity)
}
}}
答案 0 :(得分:3)
您需要覆盖onCreateOptionsMenu
中的Activity
功能,如下所示:
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menuTest, menu)
return true
}
要处理您需要覆盖onOptionsItemSelected
的菜单项上的点击事件:
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_fav -> {
// do stuff
true
}
else -> super.onOptionsItemSelected(item)
}