Domanda

I'm trying to build a drop down menu in the Action Bar Compat, as per the dev example: http://developer.android.com/guide/topics/ui/actionbar.html#Dropdown

I can't get onNavigationItemSelected to fire though.

The spinner dropdown item in the action bar is being generated, to the right of the actionbar's Title. When I press it I do see the triangle icon turn blue. The OnNavigationListener and Sting[]strings are being ran in OnCreate.

How would I get this to work?

public class Main extends ActionBarActivity {

    private ActionBar actionBar;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        spinner = new Spinner(this);
        SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this,
                R.array.operating_systems, android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(mSpinnerAdapter);

        ActionBar.OnNavigationListener mOnNavigationListener = new ActionBar.OnNavigationListener() {
            String[] strings = getResources().getStringArray(R.array.operating_systems);

            @Override
            public boolean onNavigationItemSelected(int position, long itemId) {
                ListContentFragment newFragment = new ListContentFragment();
                FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.fragment_container, newFragment, strings[position]);
                ft.commit();

                return true;
            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_share:
                Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT)
                        .show();
                break;
            case R.id.action_settings:
                Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT)
                        .show();
                break;
            default:
                break;
        }
        return true;
    }

}
È stato utile?

Soluzione

Doesn't look like you're calling ActionBar.setListNavigationCallbacks.

From step 4 in the example:

Set the callback for the drop-down list with setListNavigationCallbacks(). For example:

actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top