In an Android app, upon clicking on a menu button, MainActivity is supposed to replace an ImageView fragment with a WebView fragment. Instead, it throws:
java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.view.ViewGroup
In Eclipse I cleaned the project, deleted the R file, checked the XML files as suggested in other threads, but no luck.
If you could help, much appreciated.
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" />
I found where the problem was.
I was trying to pass the resource id of the ImageView (R.id.photoView) used to build the fragment, not the actual fragment. Since this fragment was not created from a layout, I need to use its object reference and pass its containerViewId instead:
// fragment previously created in MainActivity:
PhotoFragment f = PhotoFragment.newInstance();
So to fix the problem I substituted:
fragmentTransaction.replace(R.id.photoView, web_f);
with:
fragmentTransaction.replace(((ViewGroup)f.getView().getParent()).getId() , web_f);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With