本文介绍了使用ViewPager了一个摄像头preVIEW的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图建立一个摄像头preVIEW显示视图寻呼机有几个透明图像在preVIEW。但是,我得到这个错误:

 三月五日至10号:31:23.614:E / AndroidRuntime(674):致命异常:主要
三月5日至10日:31:23.614:E / AndroidRuntime(674):显示java.lang.NullPointerException
三月5日至10日:31:23.614:E / AndroidRuntime(674):在com.android.gs1.MainActivity $照相机preview.surfaceCreated(MainActivity.java:102)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.view.SurfaceView.updateWindow(SurfaceView.java:562)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.view.SurfaceView.access $ 000(SurfaceView.java:82)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.view.SurfaceView $ 3.on preDraw(SurfaceView.java:171)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.view.ViewTreeObserver.dispatchOn preDraw(ViewTreeObserver.java:590)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1596)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2418)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.os.Handler.dispatchMessage(Handler.java:99)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.os.Looper.loop(Looper.java:137)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在android.app.ActivityThread.main(ActivityThread.java:4340)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在java.lang.reflect.Method.invokeNative(本机方法)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在java.lang.reflect.Method.invoke(Method.java:511)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
三月5日至10日:31:23.614:E / AndroidRuntime(674):在dalvik.system.NativeStart.main(本机方法)
 

下面是我的code:

 包com.android.gs1;

进口java.io.IOException异常;
进口android.os.Bundle;
进口android.os.Parcelable;
进口android.app.Activity;
进口android.content.Context;
进口android.hardware.Camera;
进口android.support.v4.view.PagerAdapter;
进口android.support.v4.view.ViewPager;
进口android.util.Log;
进口android.view.LayoutInflater;
进口android.view.SurfaceHolder;
进口android.view.SurfaceView;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.LinearLayout;
进口android.widget.Toast;


公共类MainActivity延伸活动{

ViewPager副总裁;
相机mCamera;
SurfaceHolder mHolder;
静态诠释J;
私人vpAdapter myAdapter;
相机preVIEW preVIEW;

公共静态无效passPageNumber(int i)以{
    J =;
}
@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);


    Toast.makeText(getApplicationContext(),向左或向右滑动选择一个选项,Toast.LENGTH_LONG).show();
    VP =(ViewPager)findViewById(R.id.viewpager);
    myAdapter =新vpAdapter();
    preVIEW =新相机preVIEW(getApplicationContext(),mCamera);
    ((的LinearLayout)findViewById(R.id. preVIEW))addView(preVIEW)。
    vp.setAdapter(myAdapter);
}

私有类相机preVIEW延伸SurfaceView实现SurfaceHolder.Callback {


    私人最终字符串变量= NULL;


    公共摄像头preVIEW(上下文的背景下,相机摄像头){
        超(上下文);
        // TODO自动生成构造函数存根
        mCamera =摄像头;

        //安装SurfaceHolder.Callback所以我们得到通知时,该
        //下垫面创建和销毁。
        mHolder = getHolder();
        mHolder.addCallback(本);

        //德precated设置,但在Android上之前的版本3.0所需
      // mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @覆盖
    公共无效surfaceChanged(SurfaceHolder持有人,INT格式,诠释的宽度,
            INT高度){
        // TODO自动生成方法存根
        如果(mHolder.getSurface()== NULL){
              // preVIEW表面不存在
              返回;
            }

            在进行更改之前//停止preVIEW
            尝试 {
               mCamera.stop preVIEW();
            }赶上(例外五){
              //忽略:试图阻止一个不存在的preVIEW
            }

            //设置preVIEW大小并进行调整大小,旋转或
            //重新格式化的变化在这里

            //启动preVIEW使用新设置
            尝试 {
                mCamera.set previewDisplay(mHolder);
                mCamera.start preVIEW();

            }赶上(例外五){
                Log.d(TAG,错误启动摄像头preVIEW:+ e.getMessage());
            }
    }

    @覆盖
    公共无效surfaceCreated(SurfaceHolder持有者){
        // TODO自动生成方法存根
        尝试 {
            mCamera = Camera.open();
            mCamera.set previewDisplay(保持器);
            mCamera.start preVIEW();
        }赶上(IOException异常E){
            Log.d(TAG,错误设置摄像头preVIEW:+ e.getMessage());
        }
    }

    @覆盖
    公共无效surfaceDestroyed(SurfaceHolder持有者){
        // TODO自动生成方法存根

    }

}
私有类vpAdapter扩展PagerAdapter {

    @覆盖
    公众诠释getCount将(){
        // TODO自动生成方法存根
        返回5;
    }

    @覆盖
    公共布尔isViewFromObject(查看视图,Object对象){
        // TODO自动生成方法存根
        返回查看==((的LinearLayout)对象);
    }

    @覆盖
    公共无效destroyItem(ViewGroup中的容器,INT位置,Object对象){
        // TODO自动生成方法存根
        ((ViewPager)容器).removeView((的LinearLayout)对象);
    }

    @覆盖
    公共无效finishUpdate(集装箱的ViewGroup){
        // TODO自动生成方法存根

    }


    @覆盖
    公共对象instantiateItem(View容器,INT位置){
        // TODO自动生成方法存根
        LayoutInflater充气=(LayoutInflater)container.getContext()getSystemService(Context.LAYOUT_INFLATER_SERVICE)。
        视图V = NULL;

        开关(位置){
        情况下0:
            V = inflater.inflate(R.layout.first,NULL);
            打破;
        情况1:
            V = inflater.inflate(R.layout.second,NULL);
            打破;
        案例2:
            V = inflater.inflate(R.layout.third,NU​​LL);
            打破;
        案例3:
            V = inflater.inflate(R.layout.fourth,NULL);
            打破;
        壳体4:
            V = inflater.inflate(R.layout.fifth,NULL);
            打破;
        }


        ((ViewPager)容器).addView(五,0);
        返回伏;
    }
    @覆盖
    公共无效startUpdate(集装箱的ViewGroup){
        // TODO自动生成方法存根

    }
    @覆盖
    公共Parcelable saveState和(){
        // TODO自动生成方法存根
        返回null;
    }

}
}
 

下面是我的XML

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
的xmlns:工具=htt​​p://schemas.android.com/tool​​s
机器人:layout_width =match_parent
机器人:layout_height =match_parent
工具:上下文=。MainActivity
机器人:后台=#545454>

< android.support.v4.view.ViewPager
    机器人:ID =@ +安卓ID / viewpager
    机器人:layout_width =0dip
    机器人:layout_height =WRAP_CONTENT
    机器人:layout_weight =0.49/>
<的LinearLayout
    机器人:ID =@ + ID / preVIEW
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT>
< / LinearLayout中>
< / LinearLayout中>
 

有对viewpager五个XML。所有这些看起来是这样,但有不同的名称和标识。

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
机器人:layout_width =FILL_PARENT
机器人:layout_height =FILL_PARENT
机器人:方向=垂直
 >

< ImageView的
机器人:ID =@ + ID /此搜索
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
机器人:adjustViewBounds =假
机器人:contentDescription =@字符串/ description_image_1
机器人:scaleType =fitXY
机器人:SRC =@可绘制/第一个/>

< / LinearLayout中>
 

非常感谢你。

编辑:有人问我,我的code中的最后工作版本。在这里,它是:

 公共类MainActivity延伸活动{

ViewPager副总裁;
vpAdapter myAdapter;
摄像头摄像头= NULL;
SurfaceHolder previewHolder = NULL;
私人SurfaceView preVIEW = NULL;
私人布尔在preVIEW = FALSE;
私人布尔cameraConfigured = FALSE;
公共静态的String [] arrayURL;
公共静态布尔urlsPassed;
私人查看mContentView;
私人查看mLoadingView;

私人诠释mShortAnimationDuration;


@燮pressWarnings(德precation)
@燮pressLint(NewApi)
@覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    的setContentView(R.layout.activity_main);
    Toast.makeText(getApplicationContext(),向左或向右滑动选择一个选项,Toast.LENGTH_SHORT).show();
    //新的code

    mContentView = findViewById(R.id.content);
    mLoadingView = findViewById(R.id.loading_spinner);
    mContentView.setVisibility(View.GONE);
    mShortAnimationDuration = getResources()。getInteger(
            android.R.integer.config_shortAnimTime);
    //新的code
    preVIEW =(SurfaceView)findViewById(R.id. preVIEW);
    preview.setZOrderOnTop(假);
    previewHolder = preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

}
私人无效交叉淡入淡出(){

    //设置内容视图为0%的不透明度,但可见的,所以,它是可见
    //(但完全透明)在动画过程。
    mContentView.setAlpha(0F);
    mContentView.setVisibility(View.VISIBLE);

    //动画的内容,以100%的不透明度,并清除任何动画
    //监听器的视图设置。
    mContentView.animate()
            阿尔法(1F)
            .setDuration(mShortAnimationDuration)
            .setListener(空);

    //动画的加载,以0%的不透明度。经过动画结束,
    //设置它的知名度GONE作为优化步骤(它不会
    //参与布局传递等)
    mLoadingView.animate()
            阿尔法(0F)
            .setDuration(mShortAnimationDuration)
            .setListener(新AnimatorListenerAdapter(){
                @覆盖
                公共无效onAnimationEnd(动画动画){
                    mLoadingView.setVisibility(View.GONE);
                }
            });
}
    公共静态无效assignURL(字符串[]网址){
    arrayURL =网址;
}

    公共静态无效urlsPassed(布尔转移){
        urlsPassed =转移;
    }

@覆盖
  公共无效onResume(){
    super.onResume();
    相机= Camera.open();
}

 @覆盖
 公共布尔onCreateOptionsMenu(功能菜单){
  。getMenuInflater()膨胀(R.menu.main,菜单);
  返回true;
 }
@覆盖
  公共无效的onPause(){
    如果(在preVIEW){
      camera.stop preVIEW();
    }

    camera.release();
    摄像头= NULL;
    在preVIEW = FALSE;

    super.onPause();
  }

私人Camera.Size getBest previewSize(INT宽度,高度INT,Camera.Parameters参数){

    Camera.Size结果= NULL;
    对于(Camera.Size大小:parameters.getSupported previewSizes()){
        如果(size.width< =宽度放大器;&安培; size.height< =身高){
            如果(结果== NULL){
                结果=大小;
            }
            其他 {
                INT resultArea = result.width * result.height;
                INT newArea = size.width * size.height;

                如果(newArea> resultArea){
                    结果=大小;
                }
            }
        }
    }

    返回(结果);
}
私人无效的init preVIEW(INT宽度,高度INT){
    如果(相机= NULL和放大器;!&安培;!previewHolder.getSurface()= NULL){
      尝试 {
        camera.set previewDisplay(previewHolder);
      }
      捕获(的Throwable T){
        Log.e(previewDemo-surfaceCallback
              异常的一套previewDisplay(),T);
        吐司
          .makeText(MainActivity.this,t.getMessage(),Toast.LENGTH_LONG)
          。显示();
      }

      如果(!cameraConfigured){
        Camera.Parameters参数= camera.getParameters();
        Camera.Size大小= getBest previewSize(宽度,高度,
                                            参数);

        如果(大小!= NULL){
          parameters.set previewSize(size.width,size.height);
          camera.setParameters(参数);
          cameraConfigured = TRUE;
        }
      }
    }
  }

 私人无效开始preVIEW(){
        如果(cameraConfigured&安培;&安培;!摄像头= NULL){
          camera.start preVIEW();
          在preVIEW = TRUE;
          交叉淡入淡出();
          如果(urlsPassed){
            myAdapter =新vpAdapter(这一点,arrayURL);
            VP =(ViewPager)findViewById(R.id.viewpager);
            vp.setAdapter(myAdapter);
            vp.setCurrentItem(0);
          }
        }
      }

 SurfaceHolder.Callback surfaceCallback =新SurfaceHolder.Callback(){
        @覆盖
        公共无效surfaceCreated(SurfaceHolder持有者){
          //空操作 - 等到surfaceChanged()
        }

        @覆盖
        公共无效surfaceChanged(SurfaceHolder持有人,INT格式,诠释的宽度,高度INT){


          Camera.Parameters参数= camera.getParameters();
          parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
          camera.setParameters(参数);
          初始化preVIEW(宽,高);
          启动preVIEW();
          camera.autoFocus(空);
        }

        @覆盖
        公共无效surfaceDestroyed(SurfaceHolder持有者){
          //空操作
        }
      };

}
 

解决方案

对于未来的人,这样的问题挣扎。我找到了解决办法:

首先,无论你的preVIEW顶部设置必须放置在布局中SurfaceView后。例如:

 < RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =WRAP_CONTENT
    机器人:layout_height =WRAP_CONTENT
    工具:上下文=。MainActivity
    机器人:后台=#FFFF>

    < android.view.SurfaceView
        机器人:ID =@ + ID / preVIEW
        机器人:layout_width =4978dp
        机器人:layout_height =5131dp>
    < /android.view.SurfaceView>

    < android.support.v4.view.ViewPager
        机器人:ID =@ +安卓ID / viewpager
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =FILL_PARENT/>
< / RelativeLayout的>
 

二,在Java文件中,SurfaceView必须setZOrderOnTop为false。例如:

  SurfaceView preVIEW =(SurfaceView)findViewById(R.id. preVIEW);
preview.setZOrderOnTop(假);
 

三,设置布局,这将是对相机preVIEW上调用start preVIEW功能的摄像头后。

就是这样。

I've been trying to create a Camera Preview that displays a View Pager with several transparent images over the preview. But, I'm getting this error:

05-10 03:31:23.614: E/AndroidRuntime(674): FATAL EXCEPTION: main
05-10 03:31:23.614: E/AndroidRuntime(674): java.lang.NullPointerException
05-10 03:31:23.614: E/AndroidRuntime(674):  at com.android.gs1.MainActivity$CameraPreview.surfaceCreated(MainActivity.java:102)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.view.SurfaceView.updateWindow(SurfaceView.java:562)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.view.SurfaceView.access$000(SurfaceView.java:82)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:171)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1596)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2418)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.os.Looper.loop(Looper.java:137)
05-10 03:31:23.614: E/AndroidRuntime(674):  at android.app.ActivityThread.main(ActivityThread.java:4340)
05-10 03:31:23.614: E/AndroidRuntime(674):  at java.lang.reflect.Method.invokeNative(Native Method)
05-10 03:31:23.614: E/AndroidRuntime(674):  at java.lang.reflect.Method.invoke(Method.java:511)
05-10 03:31:23.614: E/AndroidRuntime(674):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-10 03:31:23.614: E/AndroidRuntime(674):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-10 03:31:23.614: E/AndroidRuntime(674):  at dalvik.system.NativeStart.main(Native Method)

Here is my code:

package com.android.gs1;

import java.io.IOException;
import android.os.Bundle;
import android.os.Parcelable;
import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;


public class MainActivity extends Activity {

ViewPager vp;
Camera mCamera;
SurfaceHolder mHolder;
static int j;
private vpAdapter myAdapter;
CameraPreview preview;

public static void passPageNumber(int i){
    j = i;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    Toast.makeText(getApplicationContext(), "Swipe Left or Right to Select an Option", Toast.LENGTH_LONG).show();
    vp = (ViewPager) findViewById(R.id.viewpager);
    myAdapter = new vpAdapter();
    preview = new CameraPreview(getApplicationContext(), mCamera);
    ((LinearLayout) findViewById(R.id.preview)).addView(preview);
    vp.setAdapter(myAdapter);
}

private class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{


    private final String TAG = null;


    public CameraPreview(Context context, Camera camera) {
        super(context);
        // TODO Auto-generated constructor stub
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);

        // deprecated setting, but required on Android versions prior to 3.0
      //  mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
        if (mHolder.getSurface() == null){
              // preview surface does not exist
              return;
            }

            // stop preview before making changes
            try {
               mCamera.stopPreview();
            } catch (Exception e){
              // ignore: tried to stop a non-existent preview
            }

            // set preview size and make any resize, rotate or
            // reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
                Log.d(TAG, "Error starting camera preview: " + e.getMessage());
            }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        try {
            mCamera = Camera.open();
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub

    }

}
private class vpAdapter extends PagerAdapter{

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 5;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        // TODO Auto-generated method stub
        return view == ((LinearLayout)object);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // TODO Auto-generated method stub
        ((ViewPager)container).removeView((LinearLayout)object);
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        // TODO Auto-generated method stub

    }


    @Override
    public Object instantiateItem(View container, int position) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = (LayoutInflater)container.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = null;

        switch(position){
        case 0:
            v = inflater.inflate(R.layout.first, null);
            break;
        case 1:
            v = inflater.inflate(R.layout.second, null);
            break;
        case 2:
            v = inflater.inflate(R.layout.third, null);
            break;
        case 3:
            v = inflater.inflate(R.layout.fourth, null);
            break;
        case 4:
            v = inflater.inflate(R.layout.fifth, null);
            break;
        }


        ((ViewPager)container).addView(v, 0);
        return v;
    }
    @Override
    public void startUpdate(ViewGroup container) {
        // TODO Auto-generated method stub

    }
    @Override
    public Parcelable saveState() {
        // TODO Auto-generated method stub
        return null;
    }

}
}

Here is my xml

<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"
tools:context=".MainActivity"
android:background="#545454" >

<android.support.v4.view.ViewPager
    android:id="@+android:id/viewpager"
    android:layout_width="0dip"
    android:layout_height="wrap_content"
    android:layout_weight="0.49" />
<LinearLayout
    android:id="@+id/preview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>

There are five more xml for the viewpager. All of them look like this, but with different name and ids.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
 >

<ImageView
android:id="@+id/image1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="false"
android:contentDescription="@string/description_image_1"
android:scaleType="fitXY"
android:src="@drawable/first" />

</LinearLayout>

Thank you very much

Edit: Someone asked me the final working version of my code. Here it is:

public class MainActivity extends Activity {

ViewPager vp;
vpAdapter myAdapter;
Camera camera = null;
SurfaceHolder previewHolder = null;
private SurfaceView preview = null;
private boolean inPreview = false;
private boolean cameraConfigured = false;
public static String[] arrayURL;
public static boolean urlsPassed;
private View mContentView;
private View mLoadingView;

private int mShortAnimationDuration;


@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    Toast.makeText(getApplicationContext(), "Swipe Left or Right to Select an Option", Toast.LENGTH_SHORT).show();
    //NEW CODE

    mContentView = findViewById(R.id.content);
    mLoadingView = findViewById(R.id.loading_spinner);
    mContentView.setVisibility(View.GONE);
    mShortAnimationDuration = getResources().getInteger(
            android.R.integer.config_shortAnimTime);
    //NEW CODE
    preview=(SurfaceView)findViewById(R.id.preview);
    preview.setZOrderOnTop(false);
    previewHolder=preview.getHolder();
    previewHolder.addCallback(surfaceCallback);
    previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

}
private void crossfade() {

    // Set the content view to 0% opacity but visible, so that it is visible
    // (but fully transparent) during the animation.
    mContentView.setAlpha(0f);
    mContentView.setVisibility(View.VISIBLE);

    // Animate the content view to 100% opacity, and clear any animation
    // listener set on the view.
    mContentView.animate()
            .alpha(1f)
            .setDuration(mShortAnimationDuration)
            .setListener(null);

    // Animate the loading view to 0% opacity. After the animation ends,
    // set its visibility to GONE as an optimization step (it won't
    // participate in layout passes, etc.)
    mLoadingView.animate()
            .alpha(0f)
            .setDuration(mShortAnimationDuration)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoadingView.setVisibility(View.GONE);
                }
            });
}
    public static void assignURL(String[] urls){
    arrayURL = urls;
}

    public static void urlsPassed(boolean transfer){
        urlsPassed = transfer;
    }

@Override
  public void onResume() {
    super.onResume();
    camera=Camera.open();
}

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
@Override
  public void onPause() {
    if (inPreview) {
      camera.stopPreview();
    }

    camera.release();
    camera=null;
    inPreview=false;

    super.onPause();
  }

private Camera.Size getBestPreviewSize(int width, int height,Camera.Parameters parameters) {

    Camera.Size result=null;
    for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
        if (size.width<=width && size.height<=height) {
            if (result==null) {
                result=size;
            }
            else {
                int resultArea=result.width*result.height;
                int newArea=size.width*size.height;

                if (newArea>resultArea) {
                    result=size;
                }
            }
        }
    }

    return(result);
}
private void initPreview(int width, int height) {
    if (camera!=null && previewHolder.getSurface()!=null) {
      try {
        camera.setPreviewDisplay(previewHolder);
      }
      catch (Throwable t) {
        Log.e("PreviewDemo-surfaceCallback",
              "Exception in setPreviewDisplay()", t);
        Toast
          .makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG)
          .show();
      }

      if (!cameraConfigured) {
        Camera.Parameters parameters=camera.getParameters();
        Camera.Size size=getBestPreviewSize(width, height,
                                            parameters);

        if (size!=null) {
          parameters.setPreviewSize(size.width, size.height);
          camera.setParameters(parameters);
          cameraConfigured=true;
        }
      }
    }
  }

 private void startPreview() {
        if (cameraConfigured && camera!=null) {
          camera.startPreview();
          inPreview=true;
          crossfade();
          if(urlsPassed){
            myAdapter = new vpAdapter(this,  arrayURL);
            vp = (ViewPager) findViewById(R.id.viewpager);
            vp.setAdapter(myAdapter);
            vp.setCurrentItem(0);
          }
        }
      }

 SurfaceHolder.Callback surfaceCallback=new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
          // no-op -- wait until surfaceChanged()
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) {


          Camera.Parameters parameters = camera.getParameters();
          parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
          camera.setParameters(parameters);
          initPreview(width, height);
          startPreview();
          camera.autoFocus(null);
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
          // no-op
        }
      };

}
解决方案

For future people struggling with this kind of problem. I found the solution:

First, whatever you set in top of a preview must be placed after the SurfaceView in the layout. For instance:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:context=".MainActivity"
    android:background="#ffff">

    <android.view.SurfaceView
        android:id="@+id/preview"
        android:layout_width="4978dp"
        android:layout_height="5131dp">
    </android.view.SurfaceView>

    <android.support.v4.view.ViewPager
        android:id="@+android:id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
</RelativeLayout>

Second, in the Java file, the SurfaceView must be setZOrderOnTop to false. For instance:

SurfaceView preview=(SurfaceView)findViewById(R.id.preview);
preview.setZOrderOnTop(false);

Third, set the layout that will be on the top of the CameraPreview after calling the startPreview function in camera.

That's it.

这篇关于使用ViewPager了一个摄像头preVIEW的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 23:00