轉載請註明原文地址:http://www.cnblogs.com/yanyojun/p/8082391.html 代碼已經上傳至Github:https://github.com/YanYoJun/ViewPagerDemo 先看效果 1、佈局文件 2、代碼實現 這裡需要註意點,需要先將setupW ...
轉載請註明原文地址:http://www.cnblogs.com/yanyojun/p/8082391.html
代碼已經上傳至Github:https://github.com/YanYoJun/ViewPagerDemo
先看效果
1、佈局文件
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:orientation="vertical" 8 tools:context="com.plbear.yyj.myapplication.MainActivity"> 9 10 <android.support.design.widget.TabLayout 11 android:id="@+id/tab" 12 android:layout_width="match_parent" 13 android:layout_height="40dp" 14 app:tabGravity="fill" 15 app:tabIndicatorColor="#4978ef" 16 app:tabIndicatorHeight="2dp" 17 app:tabMode="scrollable" 18 app:tabSelectedTextColor="#4978ef" 19 app:tabTextColor="#222222"></android.support.design.widget.TabLayout> 20 21 <android.support.v4.view.ViewPager 22 android:id="@+id/view_pager" 23 android:layout_width="match_parent" 24 android:layout_height="wrap_content"></android.support.v4.view.ViewPager> 25 26 </LinearLayout>
2、代碼實現
1 package com.plbear.yyj.myapplication 2 3 import android.os.Bundle 4 import android.support.design.widget.Snackbar 5 import android.support.design.widget.TabLayout 6 import android.support.v4.app.Fragment 7 import android.support.v4.app.FragmentPagerAdapter 8 import android.support.v7.app.AppCompatActivity 9 import android.view.Menu 10 import android.view.MenuItem 11 12 import kotlinx.android.synthetic.main.activity_main.* 13 14 class MainActivity : AppCompatActivity() { 15 16 var mFragList = ArrayList<Fragment>() 17 var adapter = object:FragmentPagerAdapter(supportFragmentManager){ 18 override fun getItem(position: Int): Fragment { 19 return mFragList[position] 20 } 21 22 override fun getCount(): Int { 23 return 2 24 } 25 } 26 27 override fun onCreate(savedInstanceState: Bundle?) { 28 super.onCreate(savedInstanceState) 29 setContentView(R.layout.activity_main) 30 initViewPager() //先將各個fragment加入到viewpager中 31 initTabLayout(); //初始化tablayout 32 } 33 34 35 fun initTabLayout(){ 36 tab.setupWithViewPager(view_pager) 37 tab.setTabsFromPagerAdapter(adapter) 38 tab.tabMode = TabLayout.MODE_FIXED 39 tab.getTabAt(0)?.setText("第一頁") 40 tab.getTabAt(1)?.setText("第二頁") 41 } 42 43 fun initViewPager(){ 44 mFragList.add(Fragment1()) 45 mFragList.add(Fragment2()) 46 47 view_pager.adapter = adapter 48 } 49 50 }
這裡需要註意點,需要先將setupWithViewPager和tablayout綁定起來,然後再初始化tab的標簽頁,這個非常重要,否則會造成tablayout中的文字顯示不出來。