tablayout 动态设置选中背景
时间: 2023-07-04 16:09:20 浏览: 46
可以通过设置TabLayout.Tab的自定义View来实现动态设置选中背景。具体步骤如下:
1. 首先,创建一个自定义的TabLayout.Tab的View。
```
TextView customView = (TextView) LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
```
2. 然后,在TabLayout.Tab对象上设置自定义View。
```
TabLayout.Tab tab = tabLayout.newTab();
tab.setCustomView(customView);
tabLayout.addTab(tab);
```
3. 最后,在TabLayout.Tab的自定义View上根据选中状态设置不同的背景。
```
customView.setSelected(true); // 选中状态
customView.setBackgroundResource(R.drawable.selected_bg); // 选中时的背景
```
需要注意的是,每个TabLayout.Tab都需要单独设置自定义View和选中背景,因此需要在循环中对每个Tab进行设置。完整代码示例如下:
```
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
TextView customView = (TextView) LayoutInflater.from(context).inflate(R.layout.custom_tab, null);
tab.setCustomView(customView);
if (tab.isSelected()) {
customView.setSelected(true);
customView.setBackgroundResource(R.drawable.selected_bg);
} else {
customView.setSelected(false);
customView.setBackgroundResource(R.drawable.unselected_bg);
}
}
```