为什么下面的代码强制在android项目中使用内置相机关闭?

时间:2015-01-09 13:15:40

标签: java android eclipse

package com.example.thenewjay;

import java.io.IOException;

import java.io.InputStream;

import android.app.Activity;

import android.content.Intent;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.provider.MediaStore;

import android.view.View;

import android.widget.Button;

import android.widget.ImageButton;

import android.widget.ImageView;

public class Camera extends Activity implements View.OnClickListener {

    ImageView iv;
    Button but;
    ImageButton ib;
    final static int cameraData = 0;
    Intent i;
    Bitmap bmp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        initialize();
        InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
        bmp = BitmapFactory.decodeStream(is);
    }

    private void initialize() {

        iv = (ImageView) findViewById(R.id.ivReturnedPic);
        ib = (ImageButton) findViewById(R.id.ibTakePic);
        but = (Button) findViewById(R.id.bSetWall);

        but.setOnClickListener(this);
        ib.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.bSetWall:
            try {
                getApplicationContext().setWallpaper(bmp);
                } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                }
            break;

        case R.id.ibTakePic:
            i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(i, 1);
            break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            bmp = (Bitmap) extras.get("data");
            iv.setImageBitmap(bmp);
}}
}

1 个答案:

答案 0 :(得分:1)

  

为什么在android中使用内置摄像头关闭以下代码强制   项目

因为您在致电setContentView之前遗忘了onCreate中的initialize()

您需要在调用findViewById之前设置当前活动的布局,以便在onCreate中访问当前屏幕xml.do中的视图:

...
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout_name);
initialize();
....