I'm a super beginner with 1 week of Android development history. I created a simple OptionMenu as an output. It took a long time just to implement this, so I hope it will be helpful for the same beginners.
A super-simple app that changes the displayed message when you press the save button installed at the top right of the screen
option_menu.xml
//Delete all the first default sentences and write the following
<?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/option_save"
android:title="Save"
app:showAsAction="always" />
</menu>
android: id: Key for linking layout file and java file android: text: Character string to be displayed on the main screen
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
//Just mess with id and text
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's press the save button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Think of the following two methods as rules for implementing option menus. onCreateOptionsMenu(Menu menu) onOptionsItemSelected(MenuItem item)
MainActivity.java
public class MainActivity extends AppCompatActivity {
//Leave the default ok
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Display of option menu (save button)
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// MenuInflater(A class for inflating menus to Java objects)Get
MenuInflater inflater = getMenuInflater();
// option_menu.Inflate the menu part described in xml into a Java object
inflater .inflate(R.menu.option_menu, menu);
//Return the return value
return true;
}
//Processing when the option menu (save button) is selected
@Override
public boolean onOptionsItemSelected(MenuItem item)
// activity_main.Get TextView of xml
TextView textView = findViewById(R.id.text_view);
//Set a new character string in the acquired text
textView.setText("The save button was pressed");
//Return the return value
return true;
}
}
Since I am a super beginner, please point out any differences.
・ Https://developer.android.com/guide/topics/ui/menus?hl=ja#options-menu ・ Https://qiita.com/watataku/items/5faad0384b54d0c53f6e Thank you very much!