Search code examples
androidsortingactionbarsherlock

How to toggle between ascending/descending sort in actionBar tab using ActionBarSherlock


I'm using ActionBarSherlock for my tabs in my application. I've got some items to display in the form of a list (using ArrayList) in the tabs.

Currently, I'm trying to emulate a scenario wherein I should be able to toggle between ascending and descending sort by the click on the actionBar. Has anyone tried this scenario? If yes, can anyone help me please on this?


Solution

  • After a lot of thinking and analyzing, I could achieve this in the following way.

    In the main activity file you can add the below code

    boolean flag = false;
    
    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    
             Fragment f = mFragmentList.get(tab.getPosition());
             if(f instanceof Frag_One){
                 ((Frag_All) f).toggleSortOrder(flag);
             }else if(f instanceof Frag_Due){
                 ((Frag_Two) f).toggleSortOrder(flag);
             }
             flag = !flag;
    }
    

    On doing that you need to add the below code in Frag_One and/or Frag_Two

    @Override
    public void toggleSortOrder(boolean flag) {
        // TODO Auto-generated method stub
        super.toggleSortOrder(flag);
    
        if(flag) {
            Collections.sort(list, new Comparator<CompanyInfo>() {
    
                @Override
                public int compare(CompanyInfolhs, CompanyInforhs) {
                    // TODO Auto-generated method stub
                    return lhs.getName().compareToIgnoreCase(rhs.getName());
                }
            });
            mListAdapter.notifyDataSetChanged();
        }else {
            Collections.sort(list, new Comparator<CompanyInfo>() {
    
                @Override
                public int compare(CompanyInfolhs, CompanyInforhs) {
                    // TODO Auto-generated method stub
                    return rhs.getName().compareToIgnoreCase(lhs.getName());
                }
            });
            mListAdapter.notifyDataSetChanged();
        }
    }