Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actionbar list navigation width - wrap content

By default in actionbar list navigation width of selected item is as wide as widest item. I would like to "wrap_content" in selected item as it's in google+,gmail,maps android apps.

Does someone know hot to do it?

I tried to override getView of navigation adapter but it doesn't work. It looks that this view is wrapped with another view which has width of widest item. I also tried actionbar.setCustom view with spinner but spinner behaviour is same. It uses widest item width.

Thanks for all suggestions, links and help.

Current state

Required state

like image 264
Martin Vandzura Avatar asked Feb 05 '13 16:02

Martin Vandzura


1 Answers

I've met the same problem. It seems Android will call getView() method for all the items, and finally set the width to the widest item's width.

So here's my solution:

  1. Store the current selected section(e.g. section in your example), say selectedSection, in your code. Actually you have to do it in the onNavigationItemSelected() method of NavigationListener.

  2. Override the getView() method of your SpinnerAdapter, always set it's content to selectedSection.

  3. In the onNavigationItemSelected() method of NavigationListener, try to call the notifyDataSetChanged() method of your spinnerAdapter after you set the current mode to selectedSection.

Here's the sample code:

final int selectedSection = 0;
final String sectionLabels[] = {"short sec", "long section", "looooonger section"};

final ArrayAdapter<String> arrayAdapter =
  new arrayAdapter<String>(this, simple_list_item_1) {
    @Override
    public int getCount() {
      // You need to implement here.
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      if (convertView == null) {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.you_entry, null);
      }
      TextView textView = (TextView) convertView.findViewById(R.id.you_text);
      // Set the text to the current section.
      textView.setText(sectionLabels[selectedSection]);
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
      // You need to implement here.
    }

  }

actionBar.setListNavigationCallbacks(navigationAdpater,
  new ActionBar.OnNavigationListener() {

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
      // Store the current section.
      selectedSection = itemPosition;
      navigationAdpater.notifyDataSetChanged();
      return true;
    }
  });
like image 80
Wei Jiang Avatar answered Sep 27 '22 00:09

Wei Jiang