Kotlin项目的选项卡布局具有不同的片段(FirstTab1,SecondTab1,ThirtTab1,FourthTab1,FifthTab1),在activity_main.xml中的按钮ID为“ button1”。如何使用切换按钮将这些片段替换为其他片段(FirstTab2,SecondTab2,ThirtTab2,FourthTab2,FifthTab2)
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragmentAdapter = MyPagerAdapter1(supportFragmentManager)
viewpager.adapter = fragmentAdapter
tabs.setupWithViewPager(viewpager)
}
MyPagerAdapter.kt
class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter
(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem( position: Int): Fragment {
return when (position) {
0 -> FirstTab1 ()
1 -> SecondTab1 ()
2 -> ThirtTab1 ()
3 -> FourthTab1 ()
else -> FifthTab1 ()
}
}
override fun getCount(): Int {
return 5
}
override fun getPageTitle(position: Int): CharSequence? {
return when (position){
0 -> "poniedziałek"
1 -> "wtorek"
2 -> "środa"
3 -> "czwartek"
else -> return "piątek"
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mystud.riki">
<application
android:allowBackup="true"
android:icon="@drawable/app_icon"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme.NoActionBar">
<activity android:name=".MainActivity"></activity>
<activity android:name=".SplashScreenActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
标签示例
class FirstTab1 : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first_tab1, container, false)
}
您可以在id按钮中执行操作,并在id ViewPager中使用“ setCurrentItem”。 (例如,转到“ SecondTab1”))>
[your id Button].setOnClickListener {
[your id View Pager].setCurrentItem(1, true)
}