Reputation: 201
I have implemented a FAB's setOnClickListener() in MainActivity and it is working without any issue.
I have 8 different Fragments (one shows a WebView, anoother loads a RecyclerView, etc..) based on the selection from the navigation drawer.
The FAB appears and its current action is playing a default song, which is working fine.
Now, from my 8 different Fragments, 3 Fragments show a different song list.
Since the FAB appears as default, I want to use the FAB as a play Button.
So, if the user is in one Fragment and selects a mp3 and clicks the FAB, it should play that song.
That means that I should somehow overwrite MainActivitiy's setOnClickListener with one implemented in the Fragment.
In the same way, I have other 2 Fragments which show some mp3 song list. By selecting an mp3 in that ones and clicking the FAB, the Fragment should listen for that FAB action.
Basically, the FAB should override its action and take inputs from the current Fragment.
One way I can think of is when fab.setOnClickListener is called, I will check the current Fragment and act according to that.
But the problem is to play the song, I am creating an Intent with many parameters and calling startservice.
If I can do something in the Fragment itself, I can create an Intent, bundle the required arguments etc.. on setOnClickListener().
Any suggestions to resolve my confusions is highly appreciated.
Upvotes: 1
Views: 1764
Reputation: 201
I tried below way and it is working fine. Adding it as answer to my question since it is working.
Approach:
Implemented a function with common name playAudio() in all fragments where media suppose to play. In MainActivity, onClick() of floating action button, I am checking the instance of current fragment. If it is among 3 of 8 which needs to play respective audio when fab click, i am calling the fragment's playAudio(). for rest of fragments, doing something else. Below is code snip:
@Override
onClick(View v) {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container_body);
if (fragment != null && fragment.isMenuVisible()) {
if (fragment instanceof FragmentAudioMessage) {
((FragmentAudioMessage) fragment).initPlay();
} else {
//do something else.
}
}
This way it is working differently for each fragment.
Hope this will help others.
Upvotes: 2