效果图

安卓使用TabLayout制作顶部导航栏_xml

主要代码

  1. 主界面
  • MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager.adapter = MainPagerAdapter(supportFragmentManager)
}

//ViewPager适配器 10个Fragment
private inner class MainPagerAdapter(fm: FragmentManager) :
FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(position: Int): Fragment {
return BlankFragment.newInstance(position)
}

//TabLayout会根据当前page的title自动绑定tab
override fun getPageTitle(position: Int): CharSequence? {
return "Tab $position"
}

override fun getCount(): Int {
return 10
}
}
}
  • 布局文件:activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@android:color/white"
app:tabIndicatorColor="@android:color/holo_red_light"
app:tabIndicatorHeight="2dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="@android:color/holo_red_light"
app:tabTextColor="@android:color/darker_gray" />

</androidx.viewpager.widget.ViewPager>
</LinearLayout>
  1. 空Fragment代码
  • BlankFragment.kt
class BlankFragment : Fragment() {
private var index = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = inflater.inflate(R.layout.fragment_blank, container, false)

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
textView.text = "this Tab $index"
}

companion object {
fun newInstance(position: Int): Fragment {
val fragment = BlankFragment()
fragment.index = position
return fragment
}
}
}
  • 布局文件:fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

完整源代码

https://gitee.com/cxyzy1/tab-layout-demo