Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Add action button to ActionBar

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)
    }
}}
like image 776
Torrado36 Avatar asked Mar 22 '18 13:03

Torrado36


People also ask

How do I add action to action bar?

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.

How do I add an icon to action bar in Kotlin?

Displaying ActionBar Icon Although the icon can be added back with: getSupportActionBar(). setDisplayShowHomeEnabled(true); getSupportActionBar().


1 Answers

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)
}
like image 121
Pawel Laskowski Avatar answered Oct 08 '22 05:10

Pawel Laskowski