Accessing fragment reference inside a custom view

OK. In your own words:

As per android fragments: we get context inside the constructors of the views. This context is instance of the activity. But there is no way to get reference of the fragment which is hosting the customview.

So, the context is the instance of the activity, right? Now from this activity context, i believe you can get the reference to your fragment if you had provided your fragment with a string tag name or an id using findFragmentByTag(String tag) and findFragmentById(int id) respectively.

context.getFragmentManager().findFragmentByTag("tag_of_frag_you_are_trying_to_access");

HTH.


Call FragmentManager.findFragment(this), where this is your custom view.

Or if you use Kotlin's Fragment library androidx.fragment:fragment-ktx, you can just use the extension function View.findFragment() inside your view.

It is defined as:

fun <F : Fragment> View.findFragment(): F = FragmentManager.findFragment(this)

From the documentation:

This method will locate the Fragment associated with this view. This is automatically populated for the View returned by Fragment.onCreateView and its children.