How to save and restore the state of an ExpandableListView in Android?

后端 未结 4 963
醉酒成梦
醉酒成梦 2021-01-06 12:45

Is it possible to save and restore the state (which items are collapsed and which not) of an ExpandableListView in Android?

If it is possible, how can I do that?

4条回答
  •  死守一世寂寞
    2021-01-06 12:52

    I came across this very same question and found a better answer. I have a fragment and use the onSaveInstanceState and onViewStateRestored to save and restore the ExpandableListView.

    Here I save the state of the list

    @Override
    public void onSaveInstanceState( @NonNull Bundle outState )
    {
        super.onSaveInstanceState( outState );
    
        ExpandableListView expandable = getView() != null ? getView().findViewById( R.id.expandable ) : null;
        if( expandable != null )
        {
            int groupsCount = expandable.getExpandableListAdapter()
                                        .getGroupCount();
            boolean[] groupExpandedArray = new boolean[groupsCount];
            for( int i = 0; i < groupsCount; i += 1 )
            {
                groupExpandedArray[i] = expandable.isGroupExpanded( i );
            }
            outState.putBooleanArray( "groupExpandedArray", groupExpandedArray );
            outState.putInt( "firstVisiblePosition", expandable.getFirstVisiblePosition() );
        }
    }
    

    And here I restore it when it is needed

    @Override
    public void onViewStateRestored( @Nullable Bundle savedInstanceState )
    {
        super.onViewStateRestored( savedInstanceState );
        if( savedInstanceState != null )
        {
            boolean[]          groupExpandedArray   = savedInstanceState.getBooleanArray( "groupExpandedArray" );
            int                firstVisiblePosition = savedInstanceState.getInt( "firstVisiblePosition", -1 );
            ExpandableListView expandable           = getView() instanceof ViewGroup ? getView().findViewById( R.id.expandable ) : null;
            if( expandable != null && groupExpandedArray != null )
            {
                for( int i = 0; i < groupExpandedArray.length; i++ )
                {
                    if( groupExpandedArray[i] )
                        expandable.expandGroup( i );
                }
                if( firstVisiblePosition >= 0 )
                    expandable.setSelection( firstVisiblePosition );
            }
        }
    }
    

提交回复
热议问题