Show dropdown programmatically in ActionBar / ActionBarSherlock

后端 未结 2 443
闹比i
闹比i 2020-12-09 20:10

I have an activity using ActionBarSherlock with ActionBar.NAVIGATION_MODE_LIST.

When entering the page I want the spinner in the action bar

2条回答
  •  难免孤独
    2020-12-09 20:41

    The best and easy way to implement this functionality by extending StringAdapter if you are using it. Otherwise you can take any adapter whichever you are using.

    Steps :

    • create an adapter

         class ListNavigationAdapter extends ArrayAdapter{
      
      public Spinner mSpinner; // This is the spinner which is used in actionbar
      
      public ListNavigationAdapter(Context context,
              int resource,
              int textViewResourceId, 
              String[] objects) {
          super(context, resource, 
                  textViewResourceId, objects);
          // TODO Auto-generated constructor stub
      }
      
      @Override
      public View getView(int position, 
              View convertView, 
              ViewGroup parent) {
          // TODO Auto-generated method stub
      
          mSpinner = (Spinner) parent;
      
          return super.getView(position, convertView, parent);
      }
      

      }

    • set an adapter to actionbar

    // Set up the action bar to show a dropdown list.
        actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    
        // Set up the dropdown list navigation in the action bar.
        actionBar.setListNavigationCallbacks(
                // Specify a SpinnerAdapter to populate the dropdown list.
              mAdapter = new ListNavigationAdapter(
                        actionBar.getThemedContext(),
                        android.R.layout.simple_list_item_1,
                        android.R.id.text1,
                        new String[] {
                                getString(R.string.title_1),
                                getString(R.string.title_2)
                        }),
                this);
    
    • if you want to open it as screen open, just use below mentioned code

    @Override public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        ...........
    
        if(mAdapter.mSpinner != null){
          mAdapter.mSpinner.performClick();
        }
        return true;
    }
    

    Try this . It works (Y)

提交回复
热议问题