tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF")); // setting colour but its not working
recyclerView.setBackgroundResource(R.drawable.bghomeback);
titleText.setVisibility(View.GONE);
titleText1.setVisibility(View.VISIBLE);
ContentfulAdapter.getInstance().filter("");
mSearchView.setVisibility(View.GONE);
mSearchImage.setVisibility(View.GONE);
mSearchText.setVisibility(View.GONE);
mFavText.setVisibility(View.INVISIBLE);
swipeRefresh.setOnRefreshListener(storyFragment::requestSync);
swipeRefresh.setEnabled(true);
} else if (tab.getPosition() == 1) {
titleText.setVisibility(View.VISIBLE);
titleText1.setVisibility(View.GONE);
// mRelative.setBackgroundResource(Color.parseColor("#000000"));
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
recyclerView.setBackgroundResource(R.drawable.seraback);
ContentfulAdapter.getInstance().filter("");
mSearchView.setVisibility(View.VISIBLE);
mFavText.setVisibility(View.GONE);
mSearchView.setQuery("", false);
swipeRefresh.setRefreshing(false);
swipeRefresh.setEnabled(false);
} else if (tab.getPosition() == 2){
recyclerView.setBackgroundResource(R.drawable.favback);
tabLayout.setSelectedTabIndicatorColor(R.drawable.taitemselect1);
titleText.setVisibility(View.VISIBLE);
titleText1.setVisibility(View.GONE);
// mSearchImage.setVisibility(View.GONE);
mSearchText.setVisibility(View.GONE);
mSearchView.setVisibility(View.GONE);
// ContentfulAdapter.getInstance().filter("");
// swipeRefresh.setOnRefreshListener(storyFragment::requestSync);
mFavText.setVisibility(View.VISIBLE);
mFavText.setText("The books you mark as favourite will appear in this page.\n No favourite book added.");
ContentfulAdapter.getInstance().showFavoriteItem();
if (ContentfulAdapter.getInstance().getItemCount() < 1) {
mFavText.setVisibility(View.VISIBLE);
mFavText.setText("The books you mark as favourite will appear in this page.\n No favourite book added.");
} else {
mFavText.setVisibility(View.INVISIBLE);
}
swipeRefresh.setRefreshing(false);
swipeRefresh.setEnabled(false);
}
答案 0 :(得分:3)
问题
此代码不起作用的原因是实际上您不是在更改标签的背景,而是所选标签的指示器的颜色
解决方案
由于我不确定您要实现的目标,因此我将为您提供一些有关TabLayout的有用信息。
方法TabLayout.getTabCount()
返回布局中的标签数;
方法TabLayout.getTabAt()
返回类型为TabLayout.Tab
的对象,该对象代表标签。
使用这两种方法,您可以遍历所有选项卡,并使用方法TabLayout.Tab.setCustomView(int)
或TabLayout.Tab.setCustomView(View)
为该选项卡使用自定义视图,如MarcGV回答here中所述
如果您想使用更动态的解决方案,可以使用TabLayout.getSelectedTabPosition()
获取所选标签的索引,并使用前面提到的方法获取Tab对象。
如果您只需要更改每个标签的颜色,则可以尝试执行以下操作:
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.getCustomView().setBackgroundColor(Color.parseColor(getRandomColor()));
}
我假设方法getRandomColor()
从000000到FFFFFF中选择一个值。