listview as action overflow in sherlock actionbar

后端 未结 1 426
我在风中等你
我在风中等你 2020-12-19 22:41

How to do get a listdropdown on clicking sherlock action item.It should be similar to creating spinner. But I have a problem with that approach as I dont want the selected i

1条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-19 23:00

    You can create such behavior using Spinner (or IcsSpinner for ActionBarSherlock) in action layout of a menu item. Though you have to use a little trick - hide the currently selected item.

    Create menu xml:

    
        
    

    Where res/layout-v14/my_dropdown_action_layout.xml will contain (this version is used for native action bar):

    
    
    

    and res/layout/my_dropdown_action_layout.xml will contain (this version is used for ActionBarSherlock):

    
    
    

    Using IcsSpinner is necessary to create a dropdown spinner. If you use res/layout-v14/my_dropdown_action_layout.xml layout for the default version (in res/layout/), it would behave differently on Android 2.x (the spinner would be in dialog mode).

    Now you have to fill the spinner with data properly. Just create an Activity where you inflate the menu, this way:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.my_menu, menu);
        MenuItem menuItem = menu.findItem(R.id.item1);
    
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.spinner_layout, R.id.text, items);
        adapter.setDropDownViewResource(R.layout.list_item);
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            // native ActionBar
            Spinner sp = (Spinner) menuItem.getActionView();
            sp.setAdapter(adapter);
        } else {
            // ActionBarSherlock
            IcsSpinner sp = (IcsSpinner) menuItem.getActionView();
            sp.setAdapter(adapter);
        }
    
        return super.onCreateOptionsMenu(menu);
    }
    

    Now comes the trick of hiding the currently selected item. Layout res/layout/spinner_layout.xml will contain this:

    
    
        
        
    
    

    This way you see an icon as the menu item and you have the dropdown menu. Note that layout res/layout/list_item.xml has to contain a TextView with id R.id.text too.

    Alternatively, you can use similar approach where you can use ActionProvider instead of action layout.

    And another solution would be to create custom widget similar to dropdown Spinner.

    0 讨论(0)
提交回复
热议问题