Android: изменение вкладки Цвет текста программно
У меня есть TabHost:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@android:id/tabhost"
android:background="@drawable/tabs_bg">
<LinearLayout
android:id="@+id/LinearLayout01"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<TabWidget
android:id="@android:id/tabs"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginBottom="5dip">
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</FrameLayout>
</LinearLayout>
И я добавляю табуляции к этой TabHost программно следующим образом:
tabHost = (TabHost)findViewById(android.R.id.tabhost);
tabHost.setOnTabChangedListener(this);
/* tid1 is firstTabSpec Id. Its used to access outside. */
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid2");
TabSpec ThirdTabSpec = tabHost.newTabSpec("tid3");
/* TabSpec setIndicator() is used to set name for the tab. */
/* TabSpec setContent() is used to set content for a particular tab. */
firstTabSpec.setIndicator("Tab1", getResources().getDrawable(R.drawable.tab1));
secondTabSpec.setIndicator("Tab2", getResources().getDrawable(R.drawable.tab2));
ThirdTabSpec.setIndicator("Tab3", getResources().getDrawable(R.drawable.tab3));
firstTabSpec.setContent(new Intent(this,FirstTab.class));
secondTabSpec.setContent(new Intent(this,SecondTab.class));
ThirdTabSpec.setContent(new Intent(this,ThirdTab.class));
/* Add tabSpec to the TabHost to display. */
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);
tabHost.addTab(ThirdTabSpec);
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#121312"));
}
tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#f1a026"));
И вот событие onTabChanged:
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#121312"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#f1a026"));
}
В событии onTabChanged я также хочу изменить цвет текста всех вкладок. Помогите мне, как изменить цвет текста вкладок в событии?
Спасибо,
Ответы
Ответ 1
Чтобы изменить цвет текста вкладок, вам нужно получить представление i.e TextView, которое задано как заголовок вкладок, и вы можете изменить его следующим образом:
TabHost tabhost = getTabHost();
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
{
TextView tv = (TextView) tabhost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
tv.setTextColor(.....);
}
надеюсь, что это поможет....
Ответ 2
Для нового макета вкладки поддержки дизайна; вы можете определить его в своем xml
app:tabTextColor="@color/tab_inactive" app:tabSelectedTextColor="@color/tab_active"
Э.Г. -
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabanim_tabs"
app:tabTextColor="@color/tab_inactive"
app:tabSelectedTextColor="@color/tab_active"
android:textAllCaps="false"
/>
Программно это может быть достигнуто следующим образом:
tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.color.tab_selector));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));
Ответ 3
Для меня решение @Farhan не работало, так как getChildCount()
возвращал 1
, имея четыре вкладки. Используя getTabCount()
и getChildTabViewAt()
решили это для меня:
for (int tabIndex = 0 ; tabIndex < mTabHost.getTabWidget().getTabCount() ; tabIndex ++) {
View tab = mTabHost.getTabWidget().getChildTabViewAt(tabIndex);
TextView t = (TextView)tab.findViewById(android.R.id.title);
t.setTextColor(getResources().getColor(R.color.white));
}
Я подумал, что я публикую эту альтернативу для людей, имеющих одну и ту же проблему.
Ответ 4
Когда вы используете findViewById (id), вы просите систему искать любой вид с идентификатором id " относительно для текущей ViewGroup. Это означает, что то, что вы делаете в своем коде, this.findViewById(id), поэтому оно будет искать" id" в текущем представлении. И делать findViewById (android.R.id.tabHost) не очень умно, потому что его просто не существует...
Однако, когда вы получаете getTabHost(), вы просите систему получить уникальную вкладкуHost вашей деятельности, независимо от того, что она имеет вид View как root, то есть tabHost может быть прикреплен ни к чему не вверху.
Как вывод, вы всегда должны получать getTabHost в своей TabHostActivity
Надеюсь, что я был чист.