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;
}
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");
}
}