在深入研究了 Android 的 TabHost src 之后,这里有一个相当简单的问题解决方案。它允许以图形方式“触摸”选项卡按钮,但仍保持未选中状态,并阻止对选定选项卡的任何处理(假设所有 OnTabSelected 侦听器都已知晓)。
只需扩展 TabHost 类:
public class MyTabHost extends TabHost
{
public MyTabHost(Context context)
{
super(context);
}
public MyTabHost(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void setCurrentTab(int index)
{
// e.g. substitute ? with the tab index(s) for which to perform a check.
if (index == ?)
{
if (/* a block condition exists */)
{
// Perform any pre-checking before allowing final tab selection
Toast.makeText(this.getContext(), "msg", Toast.LENGTH_SHORT).show();
return;
}
}
super.setCurrentTab(index);
}
}
然后在用于 TabActivity 的 XML中将您的引用从 TabHost 更改为MyTabHost :
<com.hos.MyTabHost
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:id="@+id/llTest"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dp"
>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="0dp"
android:layout_gravity="top"
android:layout_weight="1"
/>
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="0"
/>
</LinearLayout>
</com.hos.MyTabHost>
要记住的另一件事是,如果您在 TabActivity 中使用 TabActivity.getTabHost(),它将返回一个 MyTabHost。例如:
MyTabHost mth = (MyTabHost)getTabHost();