Android TabLayout 自定义 Indicator 示例代码
以下是一个示例代码,演示如何使用自定义视图来替代 TabLayout 的默认指示器:
// 获取 TabLayout 实例
TabLayout tabLayout = findViewById(R.id.tab_layout);
// 设置 TabLayout 的模式
tabLayout.setTabMode(TabLayout.MODE_FIXED);
// 添加 tab 选项卡
tabLayout.addTab(tabLayout.newTab().setText('Tab 1'));
tabLayout.addTab(tabLayout.newTab().setText('Tab 2'));
tabLayout.addTab(tabLayout.newTab().setText('Tab 3'));
// 获取自定义 Indicator 的布局文件
View customIndicator = getLayoutInflater().inflate(R.layout.custom_indicator, null);
// 设置自定义 Indicator 的宽度和高度
customIndicator.setMinimumWidth(0);
customIndicator.setMinimumHeight(0);
// 将自定义 Indicator 添加到 TabLayout 中
tabLayout.getTabAt(0).setCustomView(customIndicator);
// 为 TabLayout 设置监听事件,以便在 Tab 被选中时更新 Indicator 的位置
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// 获取自定义 Indicator 的视图
View customIndicator = tab.getCustomView();
if (customIndicator != null) {
// 更新自定义 Indicator 的位置
customIndicator.animate().translationY(-10).setDuration(200).start();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
View customIndicator = tab.getCustomView();
if (customIndicator != null) {
customIndicator.animate().translationY(0).setDuration(200).start();
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
在上面的示例代码中,我们首先获取了一个 TabLayout 实例,并添加了三个选项卡。然后,我们获取了一个自定义 Indicator 的布局文件,并将其设置为第一个选项卡的自定义视图。接下来,我们为 TabLayout 设置了一个监听器,在选项卡被选中或取消选中时更新自定义 Indicator 的位置。
自定义 Indicator 的布局文件可以根据需要进行更改,以满足具体的设计要求。在上面的示例代码中,我们只是使用了一个简单的视图,但您可以使用任何视图或布局文件来创建更复杂的 Indicator。
原文地址: https://www.cveoy.top/t/topic/oV4Z 著作权归作者所有。请勿转载和采集!