Fragments are managed by the Fragment Managers which are called by the Activity; so, to control what you want to do when the back button is clicked, you must do that in the activity;
Now, if you have more than one fragment set, you should use tags to find them, check to see if they are visible and if so, do what you mentioned above.
When setting your fragments, you should give them a tag and then use this tag later to findFragmentByTagName() and do an if check to see which fragment is set at the moment; Let me know if you need more help.
I hope this helped!