TabLayout+ViewPager+Fragment的使用
源代码
https://github.com/objectyan/FuelRecord
配置 app\build.gradle
1 2 3 4 5 6 7
| dependencies{ ... implementation 'com.android.support:support-v4:+' implementation 'com.android.support:appcompat-v7:+' implementation 'com.android.support:design:+' ... }
|
创建 Layout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| ... <android.support.design.widget.TabLayout android:id="@+id/home_tab" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:layout_gravity="bottom" android:background="@color/colorPrimary" android:fillViewport="false" app:tabMode="fixed" app:layout_scrollFlags="scroll" app:tabIndicatorColor="#057523" app:tabIndicatorHeight="2.0dp" app:tabSelectedTextColor="@color/colorWhile" app:tabTextColor="#ced0d3"> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/home_main_tab_overview" /> <android.support.design.widget.TabItem android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/home_main_tab_calculator" /> </android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager android:id="@+id/home_viewpager" android:layout_width="match_parent" android:layout_height="match_parent" /> ...
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package me.objectyan.fuelrecord.adapter
import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter
class HomeTabPagerAdapter(fm: FragmentManager?, var list: List<Fragment>) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment { return list.get(position) }
override fun getCount(): Int { return list.size } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| ... var tab = view.findViewById<TabLayout>(R.id.home_tab) val pager = view.findViewById<ViewPager>(R.id.home_viewpager)
val fragmentList = listOf<Fragment>(OverviewFragment(), CalculatorFragment()) pager.run { adapter = HomeTabPagerAdapter(fragmentManager, fragmentList) addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
}
}) } tab.run { setupWithViewPager(pager)
addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabSelected(tab: TabLayout.Tab) {
}
override fun onTabUnselected(tab: TabLayout.Tab) {
}
override fun onTabReselected(tab: TabLayout.Tab) {
} })
getTabAt(0)!!.setText(R.string.home_main_tab_overview) getTabAt(1)!!.setText(R.string.home_main_tab_calculator) } ...
|