【发布时间】:2012-07-11 16:04:02
【问题描述】:
我正在开发一个应用程序,分为一个库和两个应用程序:一个用于手机,另一个用于平板电脑。库中定义了很多代码和布局,应用程序中只定义了少数部分。
我在Activity 中使用片段,而ViewPager 用于手机版本(在库中定义的布局和活动,在手机应用程序中使用时没有更改)。
对于平板电脑版本,我想并排显示我的片段 (2),而不是在 ViewPager 中,所以我尝试构建这样的 XML 布局:
<....>
<LinearLayout
android:id="@+id/fragmentsParent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<fragment
android:id="@+id/f1"
android:class="com.test.Fragment1"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />
<fragment
android:id="@+id/f2"
android:name="com.test.Fragment2"
android:layout_width="0dip"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</....>
我的问题是代码在我的手机应用程序上有效,但在我的平板电脑应用程序上无效。在这一点上,我得到了这个异常堆栈:
07-11 17:41:14.032: E/AndroidRuntime(14754): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
07-11 17:41:14.032: E/AndroidRuntime(14754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1782)
07-11 17:41:14.032: E/AndroidRuntime(14754): ... 11 more
07-11 17:41:14.032: E/AndroidRuntime(14754): Caused by: java.lang.ClassCastException: com.test.Fragment1 cannot be cast to android.app.Fragment
07-11 17:41:14.032: E/AndroidRuntime(14754): at android.app.Fragment.instantiate(Fragment.java:560)
07-11 17:41:14.032: E/AndroidRuntime(14754): at android.app.Fragment.instantiate(Fragment.java:535)
07-11 17:41:14.032: E/AndroidRuntime(14754): at android.app.Activity.onCreateView(Activity.java:4168)
07-11 17:41:14.032: E/AndroidRuntime(14754): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:664)
错误消息涉及android.app.Fragment,我期望android.support.v4.app.Fragment。
在网上搜索后,我检查了以下几点:
- 我的活动扩展
android.support.v4.app.FragmentActivity, - 我的片段扩展
android.support.v4.app.Fragment, - 我的应用程序使用 support.v4 库。
【问题讨论】:
-
您是否尝试过在您的 XML 中使用完全支持库包名称,而不是
Fragment? -
我现在无法访问我的代码,但这是我尝试过的,如果我没记错的话,也发生了崩溃。我明天再试一次,我会发布引发的异常。
-
我又试了一次,结果如下:07-12 09:40:25.760: E/AndroidRuntime(4503): Caused by: java.lang.ClassCastException: android.support.v4. app.Fragment 无法转换为 android.view.View
-
你解决过这个问题吗?我也面临同样的问题。
-
没关系,在我的情况下是因为我没有在我的 Activity onCreate 中调用超类方法。
标签: android android-fragments android-support-library