简体   繁体   中英

Kotlin change menu item title doesn't work

 val menuitem=menuList!!.findItem(R.id.adres)
        menuitem.setTitle("asdklzmfkldfvsas")
        this.invalidateOptionsMenu()
        Toast.makeText(this,menuitem.title.toString(),Toast.LENGTH_LONG).show()



override fun onCreateOptionsMenu(menu: Menu?): Boolean {

        getMenuInflater().inflate(R.menu.gecmissiparis, menu);
        this.menuList=menu
        return super.onCreateOptionsMenu(menu)
    }

here is My Code . in Toast it says title is changed but the titletext doesnt change or when i try to make it invisible it doesnt go invisible i take the menu.xml from another xml not in the mainactivity.xml is this the problem? if yes how can ı solve it?

And that is the menu 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/itemxd"
        android:title="Item" />
    <item
        android:id="@+id/sipariscx"
        android:title="Item"

        >
        <menu>
            <item
                android:id="@+id/adres"
                android:title="czxzczxc" />
        </menu>
    </item>
    <item android:title="siparis1">
        <menu>
            <item android:title="adres1" />
        </menu>
    </item>
</menu>

NavigationView SEction

<com.google.android.material.navigation.NavigationView

    android:id="@+id/oldsip"

    app:headerLayout="@layout/haderdeneme"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:menu="@menu/gecmissiparis"


    >

When you call invalidateOptionsMenu it call onCreateOptionsMenu again and new menu will be recreated and whatever changes you did in menu will be lost

try updating menuitem inside onCreateOptionsMenu method

var updateTitle = true
this.invalidateOptionsMenu()
Toast.makeText(this,menuitem.title.toString(),Toast.LENGTH_LONG).show()



override fun onCreateOptionsMenu(menu: Menu?): Boolean {

        getMenuInflater().inflate(R.menu.gecmissiparis, menu);
        this.menuList=menu
        if(updateTitle)
        { 
            val menuitem=menuList!!.findItem(R.id.adres)            
            menuitem.setTitle("asdklzmfkldfvsas")
            updateTitle = false
        }
        return super.onCreateOptionsMenu(menu)
    }

Just find menu item from menu in navigationview and update title.

val navView = findViewById(R.id.Navviewid) as NavigationView
var menuItem = navView.menu.findItem(R.id.adres)
menuItem.title = "New Title"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM