So I am currently in FragmentA.java, a class which consists of different EditText
s and Checkbox
es for users to press and input.
My question is, I have this reset button, how can I reset the entire fragment view? (e.g. an EditText
will be set to empty string, or with the value 0, as it is when created).
P.S. of course I can set the editText/Checkboxes one by one programically, however there are quite a lot of them and other views, so I would like to know if there is a good way to reset all of them.
Let's break it down into steps:
1. Getting the references
How this is done depends on what you already have. If the fields are created in-code, it's easy: Just store the references in a
List<CommonBaseType>
.If they are loaded from an XML Layout, there are multiple options. If you just want all views of certain type(s) to be reset, you can iterate through the view hierarchy by getting a reference to their holding
ViewGroup
(the layout) and iterate over the children withgetChildCount()
andgetChildAt(int)
. Then, check the type of the child. If it's aViewGroup
, check it's children. If it's anEditText
orCheckBox
, add them to the list.If you need more control and don't want all views to be reset, you can tag the ones you want with something. You can tag a view in XML by using the
android:tag
-attribute and find them after inflation using theView.findViewWithTag(Object)
-method.2. Resetting
Now that you have the references, you can reset them by simply iterating over the collection you made in step 1 and handle them depending on their type. Some pseudo code with that:
Something like this will reset all fields in your form to a default-value, depending on their type.
3. Resetting back to their original values
If you want to reset the views to their original values, you should "index" those when the initial values are set (which might be directly after inflation, if you set the values via XML).
To do this, simply run through your list from step 1 and make a mapping from their ID to their value at that point:
Later when you want to reset the form-elements, you can just iterate the list again and get the default values from the map. Cast them depending on the type of field (
EditText
->String
,CheckBox
->Boolean
, etz) and set the values.Bonus: Nasty RadioGroup
Resetting a RadioGroup is simply archived by calling
clearCheck()
on it, which has the nasty side-effect of triggering the associatedOnCheckedChangeListener
(which you might not want, depending on what you're doing in the listener).The simplest way around this is to un-register the listener before calling
clearCheck()
and re-registering it afterwards. This can be archived by overridingRadioGroup.clearCheck()
: