DEV Community

Leila Oliveira
Leila Oliveira

Posted on

Criando menu de contexto para apps Android

Tutorial pá-pum pra você criar menus de contexto no Android, usando Java:

Menu "opções" no navegador.

Crie o resource file menu.xml na pasta menu

<?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/refresh_page"
        android:title="Refresh"
        app:showAsAction="always" />

</menu>
Enter fullscreen mode Exit fullscreen mode

Adicione o menu à activity

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

Adicione ação aos botões do menu

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.refresh_page:
                refreshPage();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Referências

Discussion (0)