简体   繁体   中英

Android custom view is recreated twice on orientation change, the second time without onRestoreInstanceState

I have created a custom view that is a sub-class of RelativeLayout . The view is part of a Fragment set to retain its instance state. I want to save state information (only one boolean) when the orientation of the device changes, so I implemented onSaveInstanceState and onRestoreInstanceState with my custom extension of BaseSavedState . Neither the Fragment , nor the Activity have implemented anything that deals with saving/restoring the instance state. When I change the device orientation, it saves the state, recreates the view with the saved state, but then recreates it again without calling onRestoreInstanceState .

The sequence of events goes like this, showingProgress is the boolean I want to save:

View#1 (onSaveInstanceState) showingProgress=true

View#2 (ctor) showingProgress=false
View#2 (onFinishInflate)
View#2 (onRestoreInstanceState) showingProgress=true
View#2 (showProgress)
View#2 (onSaveInstanceState) showingProgress=true

View#3 (ctor) showingProgress=false
View#3 (onFinishInflate)

After that, the view is reconstructed, but since onRestoreInstanceState is never called for View #3, it is always in its initial state.

Why does it recreate the view twice? How can I prevent the second view from recreating again, or pass the saved state along to the third view respectively?

EDIT:

Relevant parts from the Activity

private Fragment currentFragment = null;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.single_fragment);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().show();
    showLoginFragment();
}

public void showLoginFragment()
{
    final FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
    currentFragment = MyFragment.newInstance();
    t.replace(R.id.layoutRoot, currentFragment);
    t.commit();
}

The layout single_fragment.xml :

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<LinearLayout
    android:id="@+id/layoutRoot"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    </LinearLayout>
</ScrollView>

Class MyFragment

public class MyFragment extends RoboFragment
{
    // I'm using roboguice
    @InjectView(R.id.myButton) private ProgressButton myButton;

    public static MyFragment newInstance()
    {
        Bundle arguments = new Bundle();
        // no arguments for now, this comes later
        MyFragment fragment = new MyFragment();
        fragment.setArguments(arguments);
        return fragment;
    } 

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        setRetainInstance(true);
        View result = inflater.inflate(R.layout.my_fragment, container, false);
        return result;
    }
}

The layout my_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.my.package.ProgressButton
        android:id="@+id/myButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/button_caption" />

</LinearLayout>

And finally the code for the ProgressButton

/**
 * A Button with an integrated progress spinner. The button can show the progress spinner while some background process
 * is running to indicate it can't be clicked again.
 */
public class ProgressButton extends RelativeLayout
{
    /** The view holding the button text */
    private TextView textView = null;

    /** The progress spinner */
    private ProgressBar progressSpinner = null;

    private boolean showingProgress = false;

    public ProgressButton(Context context)
    {
        super(context);
        textView = new TextView(context);
        progressSpinner = new ProgressBar(context);
        initView();
    }

    public ProgressButton(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        textView = new TextView(context, attrs);
        progressSpinner = new ProgressBar(context, attrs);
        initView();
    }

    public ProgressButton(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        textView = new TextView(context, attrs, defStyle);
        progressSpinner = new ProgressBar(context, attrs, defStyle);
        initView();
    }

    /**
     * Initializes the view with all its properties.
     */
    @SuppressWarnings("deprecation")
    private void initView()
    {
        // remove the background attributes from progressbar and textview, because they should be transparent
        if (Build.VERSION.SDK_INT >= 16)
        {
            textView.setBackground(null);
            progressSpinner.setBackground(null);
        }
        else
        {
            textView.setBackgroundDrawable(null);
            progressSpinner.setBackgroundDrawable(null);
        }
    }

    @Override
    protected void onFinishInflate()
    {
        super.onFinishInflate();
        if (!isInEditMode())
        {
            progressSpinner.setVisibility(View.INVISIBLE);
        }
        RelativeLayout layout = new RelativeLayout(getContext());
        layout.setId(R.id.progressButtonContainer);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        this.addView(layout, params);

        params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_LEFT);
        params.leftMargin = 10;
        progressSpinner.setClickable(false);
        progressSpinner.setId(R.id.progressButtonProgress);
        layout.addView(progressSpinner, params);

        params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        textView.setClickable(false);
        textView.setId(R.id.progressButtonText);
        layout.addView(textView, params);
    }

    /**
     * Disables the button and shows the progress spinner.
     */
    public void showProgress()
    {
        this.setEnabled(false);
        progressSpinner.setVisibility(View.VISIBLE);
        showingProgress = true;
    }

    /**
     * Enables the button and hides the progress spinner.
     */
    public void hideProgress()
    {
        this.setEnabled(true);
        progressSpinner.setVisibility(View.INVISIBLE);
        showingProgress = false;
    }

    @Override
    public Parcelable onSaveInstanceState()
    {
        Parcelable superState = super.onSaveInstanceState();
        return new SavedState(superState, showingProgress);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state)
    {
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        showingProgress = savedState.showProgress;
        if(showingProgress)
        {
            showProgress();
        }
        else
        {
            hideProgress();
        }
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    protected void dispatchSaveInstanceState(SparseArray container) 
    {
        super.dispatchFreezeSelfOnly(container);
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    protected void dispatchRestoreInstanceState(SparseArray container) 
    {
        super.dispatchThawSelfOnly(container);
    }

    static class SavedState extends BaseSavedState
    {
        boolean showProgress = false;

        SavedState(Parcelable superState, boolean showProgress)
        {
            super(superState);
            this.showProgress = showProgress;
        }

        private SavedState(Parcel in)
        {
            super(in);
            this.showProgress = in.readByte() == 0 ? false : true;
        }

        @Override
        public void writeToParcel(Parcel out, int flags)
        {
            super.writeToParcel(out, flags);
            out.writeByte((byte) (showProgress ? 1 : 0));
        }

        // required field that makes Parcelables from a Parcel
        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>()
        {
            public SavedState createFromParcel(Parcel in)
            {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size)
            {
                return new SavedState[size];
            }
        };
    }
}

After the helpful comment by Daniel Bo, I got the solution pretty easily. The fragment is added in the activity regardless of there being a saved state or not. This causes the addition of View #3 in its initial state. Wrapping showLoginFragment(); in the Activities onCreate method in the following if loop solves the problem.

if(savedInstanceState == null)
{
    showLoginFragment();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM