FragmentStatePagerAdapter in Android
Overview
FragmentStatePagerAdapter is used to communicate between fragments. FragmentStatePagerAdapter is deprecated by the way.
Example of FragmentStatePagerAdapter
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
class FragmentAdapter(private val fragmentManager : FragmentManager) :
FragmentStatePagerAdapter(fragmentManager)
{
override fun getCount() : Int = 50
override fun getItem(position : Int) : Fragment
{
val firstFragment = FirstFragment()
val bundle = Bundle()
bundle.putString("Message" , "Message from First Fragment $position")
firstFragment.arguments = bundle
return firstFragment
}
}
class FirstFragment : Fragment()
{
override fun onCreateView(
inflater : LayoutInflater , container : ViewGroup? , savedInstanceState : Bundle?
) : View?
{
return inflater.inflate(R.layout.fragment_first , container , false)
}
override fun onStart()
{
super.onStart()
tvFirstFragmentLabel.text = arguments?.getString("Message")
}
}
class MainActivity : AppCompatActivity()
{
private lateinit var fragmentAdapter : FragmentAdapter
override fun onCreate(savedInstanceState : Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fragmentAdapter = FragmentAdapter(supportFragmentManager)
viewpager.adapter = fragmentAdapter
}
}
Comments
Post a Comment