【发布时间】:2011-05-06 20:39:42
【问题描述】:
我在我的 Android 应用程序中使用选项卡,在 HTC Sense 手机上运行该应用程序时遇到了这个问题:
Android: Highlighted tab of TabWidget not readable on HTC Sense
那里建议的解决方案(将 android:targetSdkVersion 设置为 4)并不能解决我的问题,我也不想将目标 sdk 设置为 4。
我尝试通过创建自己的标签小部件样式并修改文本颜色来解决此问题。问题是当我使用自己的风格时没有明显的区别;即样式似乎未应用于选项卡。
这是主要活动的代码,包含选项卡:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab 1").setContent(new Intent(this, Tab1.class)));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Tab 2").setContent(new Intent(this, Tab2.class)));
tabHost.setCurrentTab(0);
}
这是我的 tab.xml。请注意,我已将 MyTabStyle 指定为 TabWidget 的样式:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
style="@style/MyTabStyle"
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>
这是我在 res/values/styles.xml 中定义的 MyTabStyle 的定义:
<style name="MyTabStyle" parent="@android:style/TextAppearance.Widget.TabWidget">
<item name="android:textColor">#5DFC0A</item>
</style>
为什么我的应用程序中没有显示 MyTabStyle 的更改?解决 HTC Sense 中选定选项卡上的不可见文本的任何其他解决方案?
2011-06-02 更新
我通过使用选项卡上的文本实际上是 TextViews 的知识,设法以一种 hacky 方式解决了这个问题。将以下方法添加到您的活动中:
private void setTabColor(TabHost tabHost) {
try {
for (int i=0; i < tabHost.getTabWidget().getChildCount();i++) {
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); //Unselected Tabs
if (tv != null) {
tv.setTextColor(Color.parseColor("#ffffff"));
}
TextView tv2 = (TextView) tabHost.getCurrentTabView().findViewById(android.R.id.title); // Selected Tab
if (tv2 != null) {
tv2.setTextColor(Color.parseColor("#000000"));
}
}
} catch (ClassCastException e) {
// A precaution, in case Google changes from a TextView on the tabs.
}
}
在活动的 onCreate() 方法中添加以下内容:
// Only apply the fix if this is a HTC device.
if (android.os.Build.MANUFACTURER.toLowerCase().contains("htc")) {
// Set up the color initially
setTabColor(tabHost);
// Add a tab change listener, which calls a method that sets the text color.
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String tabId) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0);
setTabColor(tabHost);
}
});
}
【问题讨论】:
-
相关,但不完全是重复的,但对于如何设置 TabWidget 的样式有更好(更新?)的答案:stackoverflow.com/a/2805256/2291