带有DrawerLayout的InvalidCastException

时间:2013-11-15 22:15:08

标签: xamarin.android

当我给DrawerLayout充气并尝试在Activity中引用它时,我得到一个InvalidCastException。这是OnCreate中的相关代码:

SetContentView(Resource.Layout.EditProject);
View view = FindViewById (Resource.Id.editscope_main_layout);
_drawerLayout = (Android.Support.V4.Widget.DrawerLayout)view;

膨胀视图的类型是android.support.v4.widget.DrawerLayout(小写命名空间)。

这是堆栈跟踪:

System.InvalidCastException: Cannot cast from source type to destination type.
at MyProduct.MyActivity.OnCreate (Android.OS.Bundle) [0x00040] in /Users/me/code/my.domain/MyProduct/EditProjectActivity.cs:71
at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (intptr,intptr,intptr) [0x00011] in /Users/builder/data/lanes/monodroid-mlion-monodroid-4.10.1-branch/9d03ce3e/source/monodroid/src/Mono.Android/platforms/android-15/src/generated/Android.App.Activity.cs:1943
at at (wrapper dynamic-method) object.2b3da45b-0937-483d-861b-9eb3158d596a (intptr,intptr,intptr) <IL 0x00017, 0x00043>

1 个答案:

答案 0 :(得分:2)

为什么不使用FindViewById<T>之类的:

_drawerLayout = FindViewById<DrawerLayout>(Resource.Id.editscope_main_layout);

如果不起作用,请尝试:

_drawerLayout = FindViewById(Resource.Id.editscope_main_layout).JavaCast<DrawerLayout>();

前者在我的一个样本中工作正常:https://github.com/Cheesebaron/DrawerSample/blob/master/DrawerSampleActivity.cs#L31