Jan-Paul Mosterdijk Jan-Paul Mosterdijk - 4 months ago 30
Android Question

ImageButton cannot be cast to FrameLayout while i cast a Framelayout to it

I have a

fragment
with an
imagebutton
and a
framelayout
. When creating the fragment, it adds a cameraview to the framelayout. here the xml of the fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageButton
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/watchButton"
android:src="@drawable/wearc"
android:scaleType="fitCenter"
android:padding="0dp"
android:onClick="onPic"
android:contentDescription="@string/watch" />

<FrameLayout
android:id="@+id/camera_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="31.2dp">
</FrameLayout>

</LinearLayout>


And here the java script i use for the fragment:

package com.coralapps.face2face;

import android.app.Fragment;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;

public class CameraFragment extends Fragment {

android.hardware.Camera mCamera;
private CameraView mCameraView = null;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.camera_fragment, container, false);
setupCamera(v);
return v;
}

public void setupCamera(View v){
try{
mCamera = Camera.open();//you can use open(int) to use different cameras
} catch (Exception e){
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}

if(mCamera != null) {
mCameraView = new CameraView(getActivity(), mCamera);
FrameLayout camera_view = (FrameLayout) v.findViewById(R.id.camera_view);
camera_view.addView(mCameraView);
}
}
}


The error i get:

android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.FrameLayout at com.coralapps.face2face.CameraFragment.setupCamera(CameraFragment.java:41)


But on line 41, i link to R.id.camera_view, and that is clearly a Framelayout, not a Imagebutton.

Am i doing anything wrong here?

Edit: This does work when i remove the
imagebutton
.

Answer

I think the problem is that you call setupCamera(View v) in the onCreateView and pass in as a parameter a view witch is not guaranteed that is inflated yet. Instead you should grab and manipulate view's from onResume() witch is called after the view's are created . so you sould call setupCamera(v); from the onResume() method.