I am new to kotlin and I need to add action button to Action bar. I created in folder res/menu this 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>
Here is my 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>
And my Activity.kt
class DetailCar : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity)
}
}}
All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.
Displaying ActionBar Icon Although the icon can be added back with: getSupportActionBar(). setDisplayShowHomeEnabled(true); getSupportActionBar().
You need to override onCreateOptionsMenu
function in your Activity
like this:
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menuTest, menu)
return true
}
To handle click events on menu items you need to override onOptionsItemSelected
:
override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) {
R.id.action_fav -> {
// do stuff
true
}
else -> super.onOptionsItemSelected(item)
}
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