简体   繁体   中英

onRestoreInstanceState - Android View Lifecycle

I have a custom View(Group)-class called RouteAutofillControl which basically is an EditText which gets filled with the Address resolved from my current positoin. The AsyncTask gets started in the view constructor and once it's finished I remember in a member variable that the task was finished.

I also implemented state saving on configuration changes and it works.

My problem is that at the point the view constructor is called the taskCompleted member variable hasn't been retained yet so the AsyncTask starts again.

So I am looking for a method in the View lifecycle which gets called AFTER onRestoreInstanceState .

Here are the important Parts from the View:

public class RouteAutofillControl extends LinearLayout {
    private boolean taskCompleted;

    public RouteAutofillControl(Context context, AttributeSet attrs, int defStyle) {
        if(!taskCompleted) {
            new FillRouteTask(location).execute();
        }
    }   

    @Override
    public Parcelable onSaveInstanceState() {
        final Parcelable superState = super.onSaveInstanceState();
        SavedState savedState = new SavedState(superState);
        savedState.taskCompleted = taskCompleted;
        savedState.resolvedAddress = resolvedAddress;
        return savedState;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        Log.d(TAG, "onRestoreInstanceState");
        SavedState savedState = (SavedState) state;
        super.onRestoreInstanceState(savedState.getSuperState());
        taskCompleted = savedState.taskCompleted;
        resolvedAddress = savedState.resolvedAddress;
    } 
}

I did not find any information about view lifecycle methods and I am thankful for any help or advice to make it better, cheers :)

That is not quite recent, but I think that is mostly still true.

What is to retain here is that onAttachedToWindow gets called after the parent's addView process, which will call the restoreState methods on its children.

So in your case I would move my task to this callback:

@Override
public void onAttachedToWindow() {
    if(!taskCompleted) {
       new FillRouteTask(location).execute();
    }
}

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