【问题标题】:ClassCastException: ActionBarView cannot be cast to TextViewClassCastException:ActionBarView 无法转换为 TextView
【发布时间】:2012-08-17 00:09:49
【问题描述】:

我一直在使用以下解决方法将活动标签居中(无需在 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)

【问题讨论】:

  • 所以两个答案都是“正确的” :) 选择一个,我可以停止畏缩 :)

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


【解决方案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 所说的那样添加,这是一个完全的 hack,不是很健壮的代码。您应该使用 findViewById() 来定位您的视图并避免所有那些超级丑陋的投射。如果你继续沿着这条路走下去,你可以期待你的 hack 甚至我刚刚输入的代码在未来被破坏。

【讨论】:

    【解决方案2】:
    ((FrameLayout)((LinearLayout)((ViewGroup) getWindow().getDecorView()).getChildAt(0)).getChildAt(0)).getChildAt(0)
    

    从这里开始收集子视图,并搜索您自己的 TextView...您只需要跳过操作栏,无论如何,当您开始使用 hack 时,无需对此感到满意。

    【讨论】:

    • 这是一个非常糟糕的解决方法,但是嘿,如果它有效...... :) 我什至应该问为什么 findViewByID(R.whatever) 不起作用? :) 或者可能将标签附加到您的特定文本视图并运行所有视图,直到获得它。
    • @Roloc LOL 我得到了提示。我不知道为什么我这么害怕自定义标题...+1 给你们俩。
    • 请记住 1) 始终使用 getApplicationContext() 和 2) 通常不应将视图引用存储在全局变量中,因为它们会泄漏,但我还没有明白为什么这种做法被认为是不好的。
    • stackoverflow.com/questions/11254366/… 这是我在 Google 上搜索“FEATURE_PROGRESS”时的第一次点击。
    • 很高兴能帮上忙 :) 保重。
    猜你喜欢
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 2018-11-05
    相关资源
    最近更新 更多