Last active
August 22, 2019 13:51
-
-
Save douglasiacovelli/ba12467d492b2a7ee1319fc4838f81a8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class FormFragment : Fragment(), FormSection { | |
| private val section by lazy { arguments!!.getParcelable<Section>(SECTION) } | |
| private val fieldInputs = mutableListOf<FieldInput>() | |
| override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { | |
| val view = inflater.inflate(R.layout.form_section_fragment, container, false) | |
| return view | |
| } | |
| override fun onViewCreated(view: View, savedInstanceState: Bundle?) { | |
| super.onViewCreated(view, savedInstanceState) | |
| renderFields(view) | |
| } | |
| //Added function | |
| override fun onUserSubmitSection() { | |
| if (fieldInputs.validate()) { | |
| val answers = mutableListOf<Answer>() | |
| fieldInputs.forEach { | |
| answers.add(it.key, it.getValue()) | |
| } | |
| (context as SectionSubmittedListener).onSectionSubmittedWithValidAnswers(answers) | |
| } | |
| } | |
| // This is the method which does the magic | |
| private fun renderFields(view: View) { | |
| val formContainer = view.findViewById<LinearLayout>(R.id.formContainer) | |
| //We iterate through each field and decide which component it corresponds to. | |
| //All of these components created by ourselves must follow the same interface, which is FieldInput<T> | |
| section.fields.forEach { | |
| val fieldInput: FieldInput = when(it.type) { | |
| FieldType.TEXT -> { TextInput(requireContext()) } | |
| FieldType.DATE -> { DateInput(requireContext()) } | |
| else -> { | |
| throw IllegalStateException("unknown type") | |
| } | |
| } | |
| //we must set a key to each field so we send it back to the api as a map of the key and the value inserted | |
| fieldInput.apply { | |
| key = it.key | |
| setLabel(it.label) | |
| } | |
| //Then we add this field to the list of the fields, so we can validate all of them and get their values | |
| fieldInputs.add(fieldInput) | |
| //Our view only as a linear layout to hold the fields and place them one on each line | |
| formContainer.addView(fieldInput as View) | |
| } | |
| } | |
| companion object { | |
| const val SECTION = "section" | |
| fun newInstance(section: Section): FormFragment { | |
| val fragment = FormFragment() | |
| val bundle = Bundle().apply { | |
| putParcelable(SECTION, section) | |
| } | |
| fragment.arguments = bundle | |
| return fragment | |
| } | |
| } | |
| } | |
| //Added class to hold the answers | |
| data class Answer(val key: String, val value: String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment