Patty P
Patty P

Reputation: 351

Android Fragment in Layout Losing Listener

An interesting issue here. Writing an app in Kotlin (which is awesome btw) and due to customer design restraints we've had to implement a custom navigation drawer(wish we could use the native navigation view with app:menu but we can't).

Embedded fragment

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="false">
    <fragment
        android:name="com.redacted.app.nav.NavDrawerFragment"
        android:id="@+id/nav_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.design.widget.NavigationView>

// our callback
interface NavDrawerListener {
    enum class CurrentState {
        StateOne,
        StateTwo
    }
    fun onStateOneClicked()
    fun onStateTwoClicked()
}

In our case, we've created a Fragment call NavDrawerFragment that contains a RecyclerView with items and a callback interface that get hooked into in the fragment's onAttach(context: Context) method that lets the activity know the item that was clicked and any additional payloads needed to start the next activity. All works as expected, with the new activities using the same base layout and the fragments listener being implemented by the activity until... the back button is pressed. It appears that pressing back on Activity B calls onDetach on the fragment and when ActivityA resumes it the fragment instance's onAttach method never gets called again.

Am I missing something about fragments being embedded into a layout or is this behavior expected? All I need at the end of the day is for ActivityA's implementation of NavDrawerListener to be valid onResume().

Upvotes: 0

Views: 328

Answers (2)

Patty P
Patty P

Reputation: 351

Ok it turns out I quite misunderstood exactly how variables/values behave inside a companion object in kotlin. They are definitely static in nature. So what it seems actually happened was that when activity B finished and brought activity A back to the foreground that the detach method was setting the global companion object listener value to null so activity A could not access it.

Final Answer: make the listener interface variable a property of the instance vs a companion object member.

Thanks again for all the help and insight!

Upvotes: 1

Vahalaru
Vahalaru

Reputation: 400

I just went through something similar, as in weird fragment behavior. I resolved all the weird issues and errors by calling

SupportFragmentManager

The fragment itself was then still acting weird till I realized that it imported the regular fragment. Once I changed it to v4 fragment import all the weird quirks went away. This might not help but hope it does.

Upvotes: 1

Related Questions