Android Lollipop, add popup menu from title in toolbar

前端 未结 2 719

I\'m unable to see how adding a popup menu from the title is accomplished like is shown in many of the material design examples. Any help would be much appreciated.

2条回答
  •  独厮守ぢ
    2020-11-30 21:16

    I came across this question while I was trying to find a solution to prevent the popup to overlay the spinner and I would like to leave here an alternative solution to this question as its possible to add the spinner to the toolbar using the menu.xml as well

    activity_main.xml

    
    
    
    
        
    
    
    
     
    
    
    

    menu_main.xml

    
    
    
    
    
    
    
    

    Your Activity

    It will be necessary to override the onCreateOptionMenu() method, then use getMenuInflater() to inflate the menu file created earlier.

    You will also need to get the Spinner item and set an adapter to it as you would normally do.

       @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    
        getMenuInflater().inflate(R.menu.menu_main, menu);
    
        //Get Spinner item from menu
    
        MenuItem spinnerMenuItem = menu.findItem(R.id.spinner);
        final Spinner spinner = (Spinner) MenuItemCompat.getActionView(spinnerMenuItem);
    
        //Set adapter whichever way you prefer (from the resource or manually)
    
        final ArrayAdapter spinnerAdapter = ArrayAdapter
                .createFromResource(this, R.array.items_array, android.R.layout.simple_spinner_dropdown_item);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
    
        return true;
    
    }
    

    Style.xml

    Finally, if you want to customize your spinner

    
    
    
    
    
    
    

提交回复
热议问题