android.widget.ImageView无法转换为android.view.ViewGroup



在Android应用程序中,单击菜单按钮后,MainActivity应该用WebView片段替换ImageView片段。相反,它抛出:

java.lang.ClassCastException:android.widget.ImageView无法转换为android.view.ViewGroup

在Eclipse中,我清理了项目,删除了R文件,按照其他线程中的建议检查了XML文件,但没有成功。

如果你能帮忙,非常感谢。

public class MainActivity extends FragmentActivity implements PhotoFragment.Callbacks {

[…]

public void onButtonInfoClicked(int index) {
    WebFragment web_f = WebFragment.newInstance(1, "Web Fragment");
    web_f.setIndex(index);
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();       
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.replace(R.id.photoView, web_f);
    fragmentTransaction.commit();
}

fragment_photo.xml

<ImageView
    android:id="@+id/photoView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="top"
    android:scaleType="fitXY" />

web_view.xml

<WebView
    android:id="@+id/webView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="top"
    android:scaleType="fitXY" />

我找到了问题所在。

我试图传递用于构建片段的ImageView(R.id.photoView)的资源id,而不是实际片段。由于这个片段不是从布局中创建的,我需要使用它的对象引用并传递它的containerViewId:

// fragment previously created in MainActivity:
PhotoFragment f = PhotoFragment.newInstance();

因此,为了解决我取代的问题:

fragmentTransaction.replace(R.id.photoView, web_f);

带有:

fragmentTransaction.replace(((ViewGroup)f.getView().getParent()).getId() , web_f);

相关内容

最新更新