samedi 12 décembre 2015

How to build a reusable and dynamic input logic with mandatory fields in Java

I have a fragment with several spinners and sub-spinner with a certain "logic" behind it. If I make a selection in the first spinner, it could be possible that:

1.) This is already an answer and no more options are available

2.) A second spinner appears and you can choose an item in the second spinner, depending on your choice in the first spinner

3.) Even more it could be possible that the choosen item in the second spinner let an EditText appear where you can enter something

This could be an example "logic".

Spinner 1 | Spinner 2 | EditText
----------------------------------
Item 1    | -         | -            (No more input necessary, everything done)
Item 2    | Item 1    | -            (A second spinner appears...)
Item 2    | Item 2    | (Activated)  (An EditText appears after selection in Spinner2)

I hope it gets somehow clear... so my items and sub-items are saved as several string-array in strings.xml.

Like:

    <string-array name="cat1">
            <item>Item1</item>
            <item>Item2</item>
   </string-array>

   <string-array name="sub_cat1">
            <item>Item1</item>
            <item>Item2</item>
    </string-array>

    ...

I need to store them in the strings.xml because I want to make my App available in different languages. Actually I am doing something like this:

In my OnItemSelectedListener of my first spinner I check which position was selected and then I have a switch/case where I implement the logic. In the OnItemSelectedListener of the second spinner I have to do the same and implement a switch/case with the logic (e.g. if an EditText should appear or everything is fine and the user can continue)...

So everything is more or less hard-coded. I really don't like this because it is not really maintanable.. If I change the order in the string-array I have to correct every switch/case... or if I add something or delete something. But actually I don't know what would be the best way to improve this design.

I could only thing about deleting all the string-arrays in the xml and make a single item for everything (for the translation) and build a class where I can define an attribute for isMandatory or hasSubcategories or maybe hasChild.

Is there any pattern or an idea how I could create a maintable and dynamic implementation of my needs? Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire