如何在android中的片段中实现相机功能? [英] How to implement camera functionality in fragment in android?

查看:88
本文介绍了如何在android中的片段中实现相机功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在片段中有一个 button .当调用该 fragment 并单击该 button 时,我希望打开 camera .我已经完成了许多教程.但是我找不到在 fragment 中实现 camera 的解决方案.

I have a button in a fragment. when that fragment is called and clicking on that button I want the camera to open.I have gone through many tutorials. But I couldn't find the solution to implement camera in fragment.

这是我的java代码camera.java:

here is my java code camera.java:

public class camera extends Fragment {

private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
Button btnCapture;
ImageView imageView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final View rootView = inflater.inflate(R.layout.camera,
            container, false);
    btnCapture=(Button) rootView.findViewById(R.id.btnCapturePicture);
    //imageView = (ImageView) rootView.findViewById(R.id.imageview);

    btnCapture.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent,
                    CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

        }
    });

    return rootView;

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {

            Bitmap bmp = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();

            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            // convert byte array to Bitmap

            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                    byteArray.length);

            imageView.setImageBitmap(bitmap);

        }
    }
}
}

这是我的camera.xml布局:

here is my camera.xml layout:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:baselineAligned="false"
tools:context="com.example.prakash.eduqueri.fragments.camera">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical">
     <!--  Capture picture button
  -->
<Button
    android:id="@+id/btnCapturePicture"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Take a Picture"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="10dp" />

这是我的logcat:

Here is my logcat:

FATAL EXCEPTION: main
                                                                          Process: com.example.prakash.eduqueri, PID: 14511
                                                                          java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65636, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.prakash.eduqueri/com.example.prakash.eduqueri.MainActivity}: java.lang.NullPointerException
                                                                              at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
                                                                              at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
                                                                              at android.app.ActivityThread.access$1300(ActivityThread.java:141)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:136)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5052)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:515)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
                                                                              at dalvik.system.NativeStart.main(Native Method)
                                                                           Caused by: java.lang.NullPointerException
                                                                              at com.example.prakash.eduqueri.camera.onActivityResult(camera.java:87)
                                                                              at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:176)
                                                                              at android.app.Activity.dispatchActivityResult(Activity.java:5437)
                                                                              at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
                                                                              at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410) 
                                                                              at android.app.ActivityThread.access$1300(ActivityThread.java:141) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:136) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5052) 
                                                                              at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                              at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609) 
                                                                              at dalvik.system.NativeStart.main(Native Method) 

新logcat:

Unable to decode stream: java.io.FileNotFoundException: /external/images/media/24097: open failed: ENOENT (No such file or directory)

04-12 12:43:02.688 29890-29890/com.example.prakash.eduqueri I/Adreno-EGL::EGL 1.4 QUALCOMM版本:AU_LINUX_ANDROID_LNX.LA.3.5.2.2.2_RB1.04.04.04.14.154.004_msm8226_LNX.LA.3.5.2.2.2_RB1__release_AU()OpenGL ES Shader编译器版本:E031.24.00.15建立日期:14/08/06本地分支机构:mybranch4057433远程分支:quic/LNX.LA.3.5.2.2.2_rb1本地补丁:无重建分支:AU_LINUX_ANDROID_LNX.LA.3.5.2.2.2_RB1.04.04.04.154.004 + NOTHING04-12 12:43:02.848 29890-29890/com.example.prakash.eduqueri I/时间轴:时间轴:Activity_idle id:android.os.BinderProxy@424bdc50时间:262597724

04-12 12:43:02.688 29890-29890/com.example.prakash.eduqueri I/Adreno-EGL: : EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LNX.LA.3.5.2.2.2_RB1.04.04.04.154.004_msm8226_LNX.LA.3.5.2.2.2_RB1__release_AU () OpenGL ES Shader Compiler Version: E031.24.00.15 Build Date: 08/06/14 Wed Local Branch: mybranch4057433 Remote Branch: quic/LNX.LA.3.5.2.2.2_rb1 Local Patches: NONE Reconstruct Branch: AU_LINUX_ANDROID_LNX.LA.3.5.2.2.2_RB1.04.04.04.154.004 + NOTHING 04-12 12:43:02.848 29890-29890/com.example.prakash.eduqueri I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@424bdc50 time:262597724

推荐答案

如果当前片段在另一个片段中并且该片段在活动中,则首先需要在父片段或活动中定义onActivityResult,然后首先在其中定义onResultActivity父片段和父Activty.我最有可能猜到(当您使用viewPager时)您的片段位于某个片段内,而父片段位于活动内,因此请执行以下步骤:

You first need to define the onActivityResult in the parent fragment or activity if the current fragment is inside another fragment and the fragment is inside an activity then first define onResultActivity inside the parent fragment and parent Activty. most likely i guess(as you are using viewPager) your fragment is inside some fragment and that parent fragment is inside an activity so follow the following steps:

首先在Activity中定义onActivityResult,然后对片段进行细分,然后在您使用相机意图的片段中进行细分.

first define the onActivityResult inside Activity then fragment then the fragment where you are using the camera intent.

onActivityResult在父父活动中.

onActivityResult in the root parent Activity.

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
}

}

在子片段中:

  @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    for (Fragment fragment : getChildFragmentManager().getFragments()) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }    super.onActivityResult(requestCode, resultCode, data);
}

请注意:如果您的相机意图片段在该片段中,则只需执行此操作即可跳过此步骤.

Note: if if your camera intent fragment is inside this fregment then only you have to do this another skip this step.

现在终于在您的cameraIntent片段中实现了onActivityResult:

Now finally implement the onActivityResult in your cameraIntent fragment:

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == HomeActivity.RESULT_OK) {
try{
           BitmapFactory.Options options = new BitmapFactory.Options();

        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;
        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);

        imageView.setImageBitmap(bitmap); } catch (NullPointerException e) {
        e.printStackTrace();
    }           }
        } else if (resultCode == HomeActivity.RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getActivity(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getActivity(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
}

当摄像机意图开始时,在按钮的onClick中初始化fileUri变量.

The fileUri variable is initialized in onClick of button when the camera intent will start.

最后,在开始相机意图时,重要的一件事是必须使用 getParentFragment().startActivityForResult(intent,yourrequestCode);

Finally one important thing while starting your camera intent you have to usegetParentFragment().startActivityForResult(intent,yourrequestCode);

所以您的明星意图将如下所示:

so your star intent will look like:

  btnCapture.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        String fileName = System.currentTimeMillis()+".jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    fileUri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        getParentFragment().startActivityForResult(intent,
                CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

    }
});

在上述方法中,fileUri是String类型的变量,并在方法外部定义,因为它应用于设置图像的预览,如onActivityResult()所示

In above method the fileUri is a String type variable and defined outside the method as it should be used to set the preview of the image as shown in onActivityResult()

希望这会有所帮助,如果您遇到任何问题,请发表评论,我会为您提供帮助:) 编码愉快:)

Hopefully this will help, if you face any issue do comment, I will help you :) Have a happy codeing :)

这篇关于如何在android中的片段中实现相机功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆