Implementing the menu

To show the profile details and update a post, we will add two icons on the Toolbar. To do this, we need to create a toolbar file. Create a menu file in res > menu named menu_main.xml. There we will add two items, one for profile and one for updating a post.

Here is the code for menu_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/profileMenu"
android:icon="@drawable/ic_face_white_24dp"
app:showAsAction="always"
android:title="@string/title_profile">
</item>
<item
android:id="@+id/postUpdate"
android:icon="@drawable/ic_autorenew_white_24dp"
app:showAsAction="always"
android:title="@string/title_update">
</item>
</menu>

We have used app:showAsAction="always", and it means the items will always show on the toolbar.

Now implement it in MainAcitivy.kt. To do this, we need to override two functions, and these are onCreateOptionsMenu() and onOptionsItemSelected()

We will bind the menu_main menu XML file using menuInflater.inflate() in onCreateOptionsMenu(), and we will write down the logic for every menu item in the onOptionsItemSelected():

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item!!.itemId) {
R.id.profileMenu -> {
val intent = Intent(this, ProfileActivity::class.java)
startActivity(intent)
}
R.id.postUpdate -> {
getAllPosts()
}
}
return true
}

R.id.profileMenu will take you to the ProfileActivity class.

R.id.postUpdate will update the post using getAllPosts().

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.184.102