Kotlin Android Studio,未正确选择TabLayout

时间:2019-01-12 19:49:01

标签: android kotlin android-tablayout

按照这个不错的教程https://medium.com/@eijaz/getting-started-with-tablayout-in-android-kotlin-bb7e21783761

,我有一个项目正在使用viewPager使用tablayout

问题是我无法按正确的标签。

-MyPagerAdapter.kt

class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

   val fragmentList = listOf<Fragment>(ListFragment(), ScanFragment(), MinFragment(), SettingsFragment())

   override fun getItem(position: Int): Fragment {
    when (position) {
        0 -> {
            Log.d("Fragment", "Position: $position")
           return fragmentList[position]
        }
        1 -> {
            Log.d("Fragment", "Position: $position")
            return fragmentList[position]
        }
        2 -> {
            Log.d("Fragment", "Position: $position")
            return fragmentList[position]
        }
        3 -> {
            Log.d("Fragment", "Position: $position")
            return fragmentList[position]
        }
        else -> {
            throw IllegalArgumentException()
        }

    }
}

override fun getCount(): Int {
    return fragmentList.count()
}

override fun getPageTitle(position: Int): CharSequence {
    return when (position) {
        0 -> "Liste"
        1 -> "Scan"
        2 -> "Min"
        3 -> "Settings"
        else -> {
            throw IllegalArgumentException()
        }
    }
}
}

-MainActivity.kt

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val fragmentAdapter = MyPagerAdapter(supportFragmentManager)
    viewpager_main.adapter = fragmentAdapter

    mainTabbedLayout.setupWithViewPager(viewpager_main)
}
}

ListFragment.kt

class ListFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater!!.inflate(R.layout.list_fragment, container, false)
}
}

-list_fragment.xml

<FrameLayout
    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"
    tools:context="no.some.domain.ListFragment">

    <TextView android:layout_width="match_parent" android:layout_height="match_parent"
        android:text="Liste"
        android:textSize="40sp"/>

</FrameLayout>

应用启动时,Logcat会吐出以下内容:

2019-01-12 20:11:50.701 400-400/no.some.domain D/Fragment: Position: 0
2019-01-12 20:11:50.701 400-400/no.some.domain D/Fragment: Position: 1

按“扫描”选项卡时,Logcat会吐出此内容:

2019-01-12 20:40:36.847 400-400/no.some.domain D/Fragment: Position: 2

当按下Min选项卡时,Logcat会吐出以下内容:

2019-01-12 20:43:18.009 400-400/no.some.domain D/Fragment: Position: 3

按“设置”选项卡时,Logcat不会吐出任何东西。 或者,当再次按下“最小”选项卡时,什么也没有发生,或者“扫描”选项卡。

有人吗?有任何想法吗? 生命周期问题?

亲切问候 斯蒂芬

0 个答案:

没有答案