Why EditText in a custom compound view is re-using the text entered in another compound view instance?

前端 未结 6 694
一个人的身影
一个人的身影 2020-12-24 08:21

I\'m trying to write a custom compound view composed by a TextView and an EditText, _compound_view.xml_:



        
6条回答
  •  没有蜡笔的小新
    2020-12-24 08:25

    In case you have more complex compound view with many child view, you can consider overriding the dispatchSaveInstanceState of your most outer ViewGroup class and don't call the super implementation.

    Like this:

    @Override
    protected void dispatchSaveInstanceState(SparseArray container) {
        //If you don't call super.dispatchRestoreInstanceState(container) here,
        //no child view gets its state saved
    }
    

    I use this, because in my case I have hierarchy of many different compound views that have common super class in which I did this override. (I kept forgetting to set the SaveEnabled attribute to false for new layouts.) However there are many caveats, for example you need to manually save focused view and then request its focus, so your app doesn't behave oddly when screen is rotated.

    EDIT: If you actually need to save state of your compound view, overriding dispatchSaveInstanceState with an empty body will cause onSave/RestoreInstanceState not being called. If you want to use them and still not save state of any of the child views, you need to call super.dispatchFreezeSelfOnly(container) in your override.

    More on this here: http://charlesharley.com/2012/programming/views-saving-instance-state-in-android

提交回复
热议问题