Android在ImageView中更改图像?

时间:2013-07-25 15:19:29

标签: android

我有一张图片作为资源,我需要修改感谢OpenCV,然后我想把我的新图像放在原始的ImageView中。

我试过这种方式,但是:

public class VerifianceActivity extends Activity {
    /** Called when the activity is first created. */   
    private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            if (status == LoaderCallbackInterface.SUCCESS ) {
                // now we can call opencv code !

                Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.cmc7);
                Mat myMat = new Mat();
                Utils.bitmapToMat(mBitmap, myMat);

                Imgproc.cvtColor(myMat, myMat, Imgproc.COLOR_BGR2GRAY);
                Utils.matToBitmap(myMat, mBitmap);

                ImageView mIV = (ImageView) findViewById(R.id.imageView);
                mIV.setImageBitmap(mBitmap);//NPE
                //this line is suppose to work, but the app crashes.
                setContentView(R.layout.main);

            } else {
                super.onManagerConnected(status);
            }
        }
    };

    @Override
    public void onResume() {;
        super.onResume();
        OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5,this, mLoaderCallback);
        // you may be tempted, to do something here, but it's *async*, and may take some time,
        // so any opencv call here will lead to unresolved native errors.
    }
}

有什么建议吗? 我得到一个NullPointerException错误

4 个答案:

答案 0 :(得分:4)

问题是你需要打电话

setContentView(R.layout.main);

在访问任何Views之前,它们将是null,例如

 ImageView mIV = (ImageView) findViewById(R.id.imageView);

由于Views内的layout存在setContentView(),但是在layout充气之前它们不存在,因此它们会返回null如果你在膨胀Layout

之前尝试初始化它们

答案 1 :(得分:3)

你必须在findViewById之前调用setContentView,否则视图层次结构不存在,findViewById返回null

  setContentView(R.layout.main);

  ImageView mIV = (ImageView) findViewById(R.id.imageView);
  mIV.setImageBitmap(mBitmap);
  //this line is suppose to work, but the app crashes.

答案 2 :(得分:2)

我认为你必须这样做

            setContentView(R.layout.main);

之前

            ImageView mIV = (ImageView) findViewById(R.id.imageView);
            mIV.setImageBitmap(mBitmap);

答案 3 :(得分:1)

你必须致电

setContentView(R.layout.main);

在onCreate()中,至少是之前试图调用findViewById(..)

我打赌,你的imageview为null,因为它无法找到资源。

ImageView mIV = (ImageView) findViewById(R.id.imageView);