Skip to content

Instantly share code, notes, and snippets.

@douglasiacovelli
Last active August 22, 2019 13:37
Show Gist options
  • Select an option

  • Save douglasiacovelli/74fb9a6acc862839c82e6f441a0f9026 to your computer and use it in GitHub Desktop.

Select an option

Save douglasiacovelli/74fb9a6acc862839c82e6f441a0f9026 to your computer and use it in GitHub Desktop.
class FormFragment : Fragment() {
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)
}
// 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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment