[英]Android change image in a ImageView?
我有一張圖片作為資源,由於需要使用OpenCV進行修改,因此我想將新的Image放在原始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作為錯誤
問題是你需要打電話
setContentView(R.layout.main);
在訪問任何Views
之前,否則它們將為null
例如
ImageView mIV = (ImageView) findViewById(R.id.imageView);
由於Views
的內部存在layout
,你有膨脹setContentView()
他們不存在,直到那個充氣layout
,使他們將返回null
,如果你試圖在膨脹之前進行初始化Layout
您必須在setContentView
之后之前調用findViewById
,否則視圖層次結構不存在,並且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.
我想你一定要做
setContentView(R.layout.main);
之前
ImageView mIV = (ImageView) findViewById(R.id.imageView);
mIV.setImageBitmap(mBitmap);
你必須打電話
setContentView(R.layout.main);
至少在嘗試調用findViewById(..) 之前在onCreate()中
我敢打賭,您的imageview為null,因為它找不到資源。
ImageView mIV = (ImageView) findViewById(R.id.imageView);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.