Reinherd
Reinherd

Reputation: 5506

Where should the code go; in Fragment or in Activity?

Imagine this situation:

So which is the correct way of finally displaying the toast?

Case A:

public class ActivityCustom extends FragmentActivity{
    [...]
    public void sayHello(View v){
        //SHOW TOAST HERE
    }
    public void sayBye(View v){
        //SHOW TOAST HERE
    }

}

Case B:

public class ActivityCustom extends FragmentActivity{
    [...]
    public void sayHello(View v){
        ((FragmentA)this.findFragmentById(R.id.fragmentA)).showToast();
    }
    public void sayBye(View v){
        ((FragmentB)this.findFragmentById(R.id.fragmentB)).showToast();
    }

}

I'm a bit confused about that.

Because if we delegate all the work on the fragments, I guess Activity will be kinda clear of code. It will just have the code to "connect" the two fragments, right?

Upvotes: 0

Views: 218

Answers (2)

Martin Cazares
Martin Cazares

Reputation: 13705

I think this is a matter of OOP principles specifically "encapsulation", i don't think activity should contain code that do not care about, hence the proper way taking on count your example would be having each toast message in the Fragment because is their behavior and in case of modifications you actually know where to go, unlike having everything in the activity becoming the single point for every single functionality losing maintainability and extensibility, since there will be a point where all your code will rely on your activity. By the way there's nothing wrong on having Activities with just a few code, is actually good to keep code out of activity if it doesn't have to do with the activity life cycle itself...

Regards!

Upvotes: 5

MSaudi
MSaudi

Reputation: 4652

I believe you should show the toasts in each fragment. In FragmentA's onCreateView method, you get the button, add the listener and show the toast in the onCLick() method there. Same on FragmentB.

No problem for the activity to have less code.

Upvotes: 1

Related Questions