Se connecter

Edit the menu

Edit the menu

In our application, a menu already exists. This is due to the fact that we chose a layout containing a basic menu when creating our project. So here we will learn how to modify the menu, so that it opens our other activities.

Modifications: menu-main.xml

Step 1: Go to the « menu-main.xml » file.

Step 2: Use text mode to access XML

Step 3: Copy the 4 lines with the name « <item android: id …> » and copy them again just below it. You should get something like this:

modifier le menu

Modify the « id » and « title » fields with a name of your choice, this name must be declared in the « strings.xml » file in the « / res / values » folder

Modifications: strings.xml

Step 1: Go to the « strings.xml » file in the « strings » folder in « res ».

Step 2: Copy the line:

<string name="action_settings">Settings</string>

And paste the right one below, with the name you chose previously:

<string name="action_EuroVersDollar">Euro Vers Dollar</string>

Now that the changes in the xml files have been made, we have to modify our java code of the menu so that it opens our new activity when we click on « Euro to Dollar ».

To do this, open the « MainActivity » file in the Java folder and then in the first folder.

Inside of it, you should have a function:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
...
}

Then delete all that is between the braces and replace the code with:

@Override
public boolean onOptionsItemSelected(MenuItem item) 
        { switch (item.getItemId()) {
                case R.id.action_EuroVersDollar:
                       Intent EuroVersDollar = new Intent(this, EuroVersDollar.class);
// Instanciation de la première Activity 
                       this.startActivity(EuroVersDollar); // Démarrage de
l'instanciation
                       finish(); // Terminer l'Activity précédente de façon à ce que le bouton Quitter ferme tout
                       return true;
                       }
        return false;
}

Replace the occurrences of « EuroVersDollar » with the name you chose earlier. Then, it is very likely that « Intent » is highlighted in red, it is normal: the class has not yet been imported. To import it, click on « Intent » then press ALT + Enter, the class will be imported or it will be offered to you at first choice.

Now the test time has come! Launch your application and click on the menu to open your new activity, here is the expected result:

android-15

Our window opens up as planned!

It’s just a little bit empty … then go to the next part!

TOUT VOIRAjouter une remarque
VOUS
Ajouter votre commentaire

Chercher un cours

Publicité

FREEDOM SUBSTITUTE | 2015-2019

Si vous souhaitez interagir directement avec notre communauté, rendez-vous sur discord :

https://discord.gg/Hm5gEGA

FREEDOM SUBSTITUTE

38 Utilisateurs en ligne