1

Background: I am trying to have an edit "button" (that is, a menu item) in the Action Bar, which would toggle between a TextView and an EditText. I got that working. Now, I'm trying to make the text in the button change to "save" after it is clicked.

The Problem: I cannot findById the menu item - it returns null. Could anyone tell me what am I doing wrong?

Here is the menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/itEdit"
        android:title="EDIT"
        app:showAsAction="always"
        />
</menu>

Here is the menu setup (i.e. extending the action bar)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_written_note, menu);
    return true;
}

@Override
public boolean onMenuOpened(int featureId, Menu menu){
    // A global variable s.t. I could refer to it and update the text
    itEdit = findViewById(R.id.itEdit);
    return true;
}

Here's the toggling part:

public void toggleEdit() {
    if(isEditing) {
        // Editing -> Viewing

        // Toggling TextView and EditText

        if(itEdit != null) { // It is always null
            itEdit.setTitle("EDIT");
        }
    } else {
        // Viewing -> Editing

        // Toggling TextView and EditText

        if(itEdit != null) { // It is always null
            itEdit.setTitle("SAVE");
        }
    }
    isEditing = !isEditing;
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Omer Lubin
  • 551
  • 2
  • 8
  • 24
  • Check this answer: https://stackoverflow.com/questions/7066657/android-how-to-dynamically-change-menu-item-text-outside-of-onoptionsitemssele#answer-7066901 – Akshay Nov 04 '19 at 13:12
  • @AlexanderHoffmann Thank you, that's what I did wrong. No idea how I missed this post – Omer Lubin Nov 04 '19 at 13:18

1 Answers1

0

You are referencing the menu item from the wrong place. The following solution should work.

public class TestActivity extends AppCompatActivity {

  private Menu menu;

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_written_note, menu);

    this.menu = menu;

    return true;
  }

  private void updateMenuTitle() {
    MenuItem item = menu.findItem(R.id.itEdit);
    item.setTitle("Test");
  }

}
Prokash Sarkar
  • 11,723
  • 1
  • 37
  • 50