Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How EditText Retains its value but not textview when phone orientation changes?

What is so special about Edittext that it can retain the value but not Textview and some other widgets and we have to use onSavedInstance() method for them.

What is the magic behind EditText specially that it can retain the values?

If someone can tell how it works internally.

<----Update---->

How it works internally, Please point to that part of the code which explains this scenario.

like image 624
Hisham Muneer Avatar asked Mar 21 '13 10:03

Hisham Muneer


1 Answers

By default, EditText view saves its state - This is accomplished by setting flags in code telling the view to save state when view is not visible or lost focus. The text is automatically saved and restored after rotating device. The automatic saving of state of EditText view can be disabled in the XML layout file by setting the android:saveEnabled property to false:

 android:saveEnabled="false"

Or programmatically, call view.setSaveEnabled(false).

saveEnabled controls whether the saving of this view's state is enabled (that is, whether its onSaveInstanceState() method will be called). Note that even if freezing is enabled, the view still must have an id assigned to it (via setId()) for its state to be saved. This flag can only disable the saving of this view; any child views may still have their state saved. saveEnabled attribute is part of android View - View Code. Here is related parts of code:

public boolean isSaveEnabled() {
        return (mViewFlags & SAVE_DISABLED_MASK) != SAVE_DISABLED;
    }

...

 public void setSaveEnabled(boolean enabled) {
        setFlags(enabled ? 0 : SAVE_DISABLED, SAVE_DISABLED_MASK);
    }

...

 void setFlags(int flags, int mask) {
        int old = mViewFlags;
        mViewFlags = (mViewFlags & ~mask) | (flags & mask);

        int changed = mViewFlags ^ old;
        if (changed == 0) {
            return;
        }
        int privateFlags = mPrivateFlags;

        /* Check if the FOCUSABLE bit has changed */
        if (((changed & FOCUSABLE_MASK) != 0) &&
                ((privateFlags & HAS_BOUNDS) !=0)) {
            if (((old & FOCUSABLE_MASK) == FOCUSABLE)
                    && ((privateFlags & FOCUSED) != 0)) {
                /* Give up focus if we are no longer focusable */
                clearFocus();
            } else if (((old & FOCUSABLE_MASK) == NOT_FOCUSABLE)
                    && ((privateFlags & FOCUSED) == 0)) {
                /*
                 * Tell the view system that we are now available to take focus
                 * if no one else already has it.
                 */
                if (mParent != null) mParent.focusableViewAvailable(this);
            }
        }

....

like image 167
Wildroid Avatar answered Nov 15 '22 18:11

Wildroid