Click the action bar icon to open a new try

1

I would like to know how to click on the icon / word in the action bar and it opens a new intent.

I'm doing the following:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.marcas:
            Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT)
                    .show();
            break;
        }

    return true;
}

It returns me the message of how I clicked the icon, but would like to open a new attempt.

    
asked by anonymous 17.06.2016 / 19:33

1 answer

2

You can do this:

public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.menueditar) {

            Intent iedicao = new Intent(MainActivity.this, paginadeedicao.class);

            startActivity(iedicao);
            MainActivity.this.finish();
            return true;
        }
    }
    return super.onOptionsItemSelected(item);
}

where:

                Intent iedicao = new Intent(MainActivity.this, paginadeedicao.class);

You create a new intent with the name in this case that goes from mainActivity (current activity) to paginadeedicao.class (which is another page of the code)

You can also send parameters with extra put:

    iedicao.putExtra("pagina", page);

must come before startActivity.

Are you inflating the menu?

//coloca os ícones no menu
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if(featureId == Window.FEATURE_ACTION_BAR && menu != null){
            if(menu.getClass().getSimpleName().equals("MenuBuilder")){
                try{
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch(NoSuchMethodException e){
                } catch(Exception e){
                    throw new RuntimeException(e);
                }
            }
        }

        return super.onMenuOpened(featureId, menu);
    }
    //cria todos os menus
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        onMenuOpened(Window.FEATURE_ACTION_BAR, menu);
        return true;
    }
    //seta as opções de função dos itens do menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.menueditar) {

            startActivity(new Intent(MainActivity.this, edicao.class));
            MainActivity.this.finish();

            return true;
        }
    }
    return super.onOptionsItemSelected(item);
}

this

startActivity(new Intent(MainActivity.this, edicao.class));

is like this

Intent iedicao = new Intent(MainActivity.this, paginadeedicao.class);

startActivity(iedicao);
    
17.06.2016 / 19:51