ClassCastException:ActionBarView无法强制转换为TextView

时间:2012-08-16 15:56:57

标签: android android-layout android-actionbar textview classcastexception

我一直在使用以下解决方法来集中活动标签(无需借助XML布局中的自定义标题):

((TextView)((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);

这很有效,但每隔一段时间我就会看到其中一位用户(在Google Play上)获得

  

java.lang.ClassCastException:   com.android.internal.widget.ActionBarView无法强制转换为   android.widget.TextView

这些可能是运行Android 3.x或更高版本的平板电脑用户。

如果没有实现我自己的自定义标题可以直接访问活动标签,您是否可以推荐另一种方法来避免ActionBarViewTextView ClassCastException?

也许检查应用程序当前运行的Android版本,然后查看getChildAt(0)的其他级别?

2 个答案:

答案 0 :(得分:1)

操作栏在主题中定义。因此,如果你想避免那种出现,你需要选择不同的主题。

或者,您可以检测用户正在使用的操作系统版本,如果是11(Honeycomb)或更高版本,只需跳过操作栏并获取下一个视图即可。

这看起来像

if (Integer.valueOf(android.os.Build.VERSION.SDK) > 11)
{
    ((TextView)((FrameLayout)((LinearLayout)((ViewGroup).getWindow().getDecorView()).getChildAt(1)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);
}
else
   ((TextView)((FrameLayout)((LinearLayout)((ViewGroup).getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)).setGravity(Gravity.CENTER);
我还想像Shark一样补充说,这是一个完全破解而且代码不是很强大的。您应该使用findViewById()来查找您的视图并避免所有那些超级丑陋的转换。如果继续沿着这条路走下去,你可以期待你的黑客甚至我刚刚放入的代码。

答案 1 :(得分:1)

((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)

从这里开始收集子视图,并搜索您自己的TextView ...您只需要跳过操作栏,无论如何当您开始使用黑客时都不需要对它进行好处。