怎么在TabLayout控件中加入图片
时间: 2024-05-15 19:15:29 浏览: 15
可以通过以下代码在TabLayout控件中添加图片:
1. 在布局文件中添加TabLayout控件:
```
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
app:tabMode="scrollable"
app:tabTextColor="@android:color/white"
app:tabSelectedTextColor="@android:color/white"
app:tabIndicatorHeight="0dp" />
```
2. 在代码中设置TabLayout的标签和图标:
```
TabLayout tabLayout = findViewById(R.id.tab_layout);
// 添加标签和图标
tabLayout.addTab(tabLayout.newTab().setText("Tab 1").setIcon(R.drawable.tab_icon_1));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2").setIcon(R.drawable.tab_icon_2));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3").setIcon(R.drawable.tab_icon_3));
// 设置TabLayout的监听器
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// 当标签被选中时执行的操作
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// 当标签失去焦点时执行的操作
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
// 当标签被重新选中时执行的操作
}
});
```
注意:在设置图标时,需要将图片放置在res/drawable目录下。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)