Is there an Android design pattern for handling multiple fragments in one action?

I have inherited some code at work, and I have a question about some implementation. In the application in which I work, there is an Activity that contains about 15 different fragments. The logic in the Office that processes these fragments can be roughly summed with the following pseudo-code:

if (button_1 selected) { load fragment_1; } else if (button_2 selected) { load fragment_2; } else if (button_3 selected) { load fragment_3; } ...and so on x15ish 

My question is: is there some kind of Android design template to handle such situations? The code works; however, I don't feel too comfortable with a giant if / else or case statement. I saw this question and it seems very similar to the problem I am facing. I searched quite a bit on the Internet, but I did not find any examples or best practices for such a scenario.

If someone can point me in the right direction or offer me some suggestions; it would be great. Thanks!

+5
source share
2 answers

You do not have to check which button was selected, but use the onClickListener button to select the correct fragment.

 buttonForFragment1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // select fragment 1 here } }); 

As for the question, this is not the level of design patterns, but implementation details (idioms), and you correctly recognized your code as a smell, and I think one of the possible solutions that does not qualify as a template is the code above.

0
source

For each button in the layout, you can assign a method in your activity:

 <Button ... android:onClick="startFragmentOne" /> 

Then we implement these methods:

 public void startFragmentOne(View view) { //TODO } 
0
source

Source: https://habr.com/ru/post/1247911/


All Articles