Getting the current Fragment instance in the viewpager

前端 未结 30 1935
醉话见心
醉话见心 2020-11-22 08:56

Below is my code which has 3 Fragment classes each embedded with each of the 3 tabs on ViewPager. I have a menu option. As shown in the onOpt

30条回答
  •  灰色年华
    2020-11-22 09:04

    Based on what he answered @chahat jain :

    "When we use the viewPager, a good way to access the fragment instance in activity is instantiateItem(viewpager,index). //index- index of fragment of which you want instance."

    If you want to do that in kotlin

    val fragment =  mv_viewpager.adapter!!.instantiateItem(mv_viewpager, 0) as Fragment
                    if ( fragment is YourFragmentFragment)
                     {
                        //DO somthign 
                     }
    

    0 to the fragment instance of 0

    //=========================================================================// //#############################Example of uses #################################// //=========================================================================//

    Here is a complete example to get a losest vision about

    here is my veiewPager in the .xml file

       ...
        
        ...
    

    And the home activity where i insert the tab

    ...
    import kotlinx.android.synthetic.main.movie_tab.*
    
    class HomeActivity : AppCompatActivity() {
    
        lateinit var  adapter:HomeTabPagerAdapter
    
        override fun onCreate(savedInstanceState: Bundle?) {
           ...
        }
    
    
    
        override fun onCreateOptionsMenu(menu: Menu) :Boolean{
                ...
    
            mSearchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
              ...
    
                override fun onQueryTextChange(newText: String): Boolean {
    
                    if (mv_viewpager.currentItem  ==0)
                    {
                        val fragment =  mv_viewpager.adapter!!.instantiateItem(mv_viewpager, 0) as Fragment
                        if ( fragment is ListMoviesFragment)
                            fragment.onQueryTextChange(newText)
                    }
                    else
                    {
                        val fragment =  mv_viewpager.adapter!!.instantiateItem(mv_viewpager, 1) as Fragment
                        if ( fragment is ListShowFragment)
                            fragment.onQueryTextChange(newText)
                    }
                    return true
                }
            })
            return super.onCreateOptionsMenu(menu)
        }
            ...
    
    }
    

提交回复
热议问题