用Fragment和viewpage2写个例子
时间: 2024-05-05 16:14:57 浏览: 141
好的,我能够帮您进行开发相关的问题,以下是一个简单的示例。
首先,您需要在您的项目中添加以下依赖项:
```
implementation 'androidx.viewpager2:viewpager2:1.0.0'
```
其次,创建一个包含两个Fragment的ViewPager2,分别是Fragment1和Fragment2,如下所示:
```kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val viewPager2 = findViewById<ViewPager2>(R.id.viewPager2)
viewPager2.adapter = ViewPagerAdapter(this)
}
}
class ViewPagerAdapter(activity: FragmentActivity) : FragmentStateAdapter(activity) {
private val fragmentList = arrayListOf(Fragment1(), Fragment2())
override fun getItemCount(): Int {
return fragmentList.size
}
override fun createFragment(position: Int): Fragment {
return fragmentList[position]
}
}
class Fragment1 : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment1_layout, container, false)
}
}
class Fragment2 : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment2_layout, container, false)
}
}
```
最后,在两个布局文件中定义您需要的视图,例如:
fragment1_layout.xml:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is Fragment 1" />
</LinearLayout>
```
fragment2_layout.xml:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is Fragment 2" />
</LinearLayout>
```
以上示例简单地演示了如何使用ViewPager2和Fragment来创建多个屏幕滑动的用户界面。希望对您有所帮助!
阅读全文