Tuesday, 5 November 2019

Scrolling to top of particular view causes NPE in Fragment?

I have an activity and a fragment. I have two buttons in the activity and on click of both the buttons I am loading the same fragment. On Second button click I want to scroll to a textview's top position and the fragment has NestedScrollView as its parent.

I am using interface to differentiate between which button was clicked

interface HomeFragmentListener {
    fun shouldScrollToCampaign(scroll: Boolean)
}

class MainActivity : AppCompatActivity(),... {

private var homeFragmentListener: HomeFragmentListener? = null

    fun setHomeFragmentListener(homeFragmentListener: HomeFragmentListener? ){
       this.homeFragmentListener = homeFragmentListener
    }

}

Following is my second button click code

loadFragment(HomeFragment())
homeFragmentListener?.shouldScrollToCampaign(true)

The fragment loading is as follows

private fun loadFragment(fragment: Fragment?) {
        val transaction = supportFragmentManager.beginTransaction()
        fragment?.let { transaction.replace(R.id.fl_activity_main, it) }
        transaction.commit()
    }

My Fragment is as follows

class HomeFragment : Fragment(), HomeFragmentListener {

   override fun shouldScrollToCampaign(scroll: Boolean) {
        if (scroll) {
            nestedScrollView {
                nsv_fragment_home.scrollTo(
                    0,
                    textView.top
                )
            }
        }
    }

 override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        (activity as MainActivity).setHomeFragmentListener(this)
..}

}

I am also calling Network Code when fragment is loaded



from Scrolling to top of particular view causes NPE in Fragment?

No comments:

Post a Comment