Search code examples
androidandroid-fragmentssearchviewandroid-context

how to get fragment object from context


Is it possible to get the fragment object from the context object? I am basically trying to access the fragment object from a SearchView class that i extended. Since context is the only object passed to the SearchView constructor, i was hoping to somehow get a reference to the fragment from it.

I know that we can get it from within an activity by using getSupportFragmentManager().findFragmentById(R.id.xxx). But getSupportFragmentManager() is available only in a FragmentActivity class. Is there someway to access the fragment from another class?


Solution

  • If you don't mess with the normal way a View is built then the Context reference that you receive in the constructor of a View is the Activity(a Context) where the View is being used. So, you have the option of casting that Context to an Activity reference and from there you can use one of the various ways to access the desired Fragment.