Hızlı yanıt: kod örneği
stackoverflow.com proper-implementation-of-viewpager2-in-android
Actually now there is an official samples repo for ViewPager2 (linked below)MainActivity.ktFirstFragment.kt ( and looks similar to )ViewPagerAdapter.ktSome other useful resources:
- https://github.com/android/views-widgets-samples/tree/master/ViewPager2
- ViewPager2 with Views - shows how to set up a ViewPager2 with Views as pages
- ViewPager2 with Fragments - shows how to set up a ViewPager2 with Fragments as pages
- ViewPager2 with a Mutable Collection (Views) - demonstrates usage of ViewPager2 with Views as pages and mutations in a page adapter
- ViewPager2 with a Mutable Collection (Fragments) - demonstrates usage of ViewPager2 with Fragments as pages, and mutations in a page adapter
- ViewPager2 with a TabLayout (Views) - shows how to set up a ViewPager2 with Views as pages, and link it to a TabLayout
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".MainActivity"> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/pager2_container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/></LinearLayout>
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val viewPager2 = findViewById<ViewPager2>(R.id.pager2_container) val fragmentList = arrayListOf( FirstFragment.newInstance(), SecondFragment.newInstance(), ThirdFragment.newInstance() ) viewPager2.adapter = ViewPagerAdapter(this, fragmentList) }}
SecondFragment.kt
ThirdFragment.kt
FirstFragment.kt
class FirstFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_first, container, false) } companion object{ fun newInstance() = FirstFragment() }}
class ViewPagerAdapter(fa:FragmentActivity, private val fragments:ArrayList<Fragment>): FragmentStateAdapter(fa) { override fun getItemCount(): Int = fragments.size override fun createFragment(position: Int): Fragment = fragments[position]}
- API reference: https://developer.android.com/reference/androidx/viewpager2/widget/ViewPager2
- Training: https://developer.android.com/training/animation/screen-slide-2
- Release notes: https://developer.android.com/jetpack/androidx/releases/viewpager2
- Medium article by a GDE : Exploring the ViewPager2