我有fragment
imagebutton
和framelayout
。创建片段时,它会将frameview添加到framelayout。这里是片段的xml:
<?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>
这里是我用于片段的java脚本:
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);
}
}
}
我得到的错误:
android.support.v7.widget.AppCompatImageButton cannot be cast to android.widget.FrameLayout at com.coralapps.face2face.CameraFragment.setupCamera(CameraFragment.java:41)
但是在第41行,我链接到R.id.camera_view,这显然是一个Framelayout,而不是一个Imagebutton。
我在这里做错了吗?
编辑:当我删除imagebutton
时,这会有效。
答案 0 :(得分:0)
private CameraView mCameraView = null;
通过初始化它就像你说它是CameraView,而不是FrameLayout。尝试用CameraView替换FrameLayout。如果它不像FrameLayout,LinearLayout等(在左侧列出),请尝试将其添加为自定义视图
答案 1 :(得分:0)
兄弟,运行时代码没有错误!但我改变了这一行
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) {
//change
// mCameraView = new CameraView(getActivity(), mCamera);
FrameLayout camera_view = (FrameLayout) v.findViewById(R.id.camera_view);
camera_view.addView(mCameraView);
}
}
答案 2 :(得分:0)
我认为问题在于你在setupCamera(View v)
中调用了onCreateView
并作为参数传递了一个视图,但是不能保证它已经膨胀了。相反,您应该在创建视图后调用onResume()
来捕获和操纵视图。所以你可以从setupCamera(v);
方法拨打onResume()
。