安卓开发使用com.google.android.material.tabs.TabLayout,动态添加TabItem。请用kotlin写出个简单的案例
时间: 2024-05-06 10:18:34 浏览: 245
好的,以下是一个使用 Kotlin 动态添加 TabItem 到 TabLayout 的简单案例:
首先,在 XML 布局文件中添加 TabLayout 控件:
```xml
<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable" />
```
接着,在 Kotlin 文件中获取 TabLayout 控件的实例,然后使用 addTab() 方法动态添加 TabItem,并设置它们的文本和图标:
```kotlin
val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
// 添加三个 TabItem
val tab1 = tabLayout.newTab()
tab1.text = "Tab 1"
tab1.setIcon(R.drawable.tab_icon_1)
tabLayout.addTab(tab1)
val tab2 = tabLayout.newTab()
tab2.text = "Tab 2"
tab2.setIcon(R.drawable.tab_icon_2)
tabLayout.addTab(tab2)
val tab3 = tabLayout.newTab()
tab3.text = "Tab 3"
tab3.setIcon(R.drawable.tab_icon_3)
tabLayout.addTab(tab3)
```
以上代码会在 TabLayout 中添加三个可滚动的 TabItem,每个 TabItem 都有一个文本和一个图标。你可以根据需要自定义 TabItem 的样式和布局。
阅读全文
相关推荐















