【问题标题】:image won't show on inflated ImageView图像不会显示在膨胀的 ImageView 上
【发布时间】:2016-01-11 08:18:09
【问题描述】:
我正在尝试在 ImageView 上为我通过相机拍摄的照片充气,但获得了 NPE。
public void onDescriptionClick(){
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.camap);
View view = getLayoutInflater().inflate(R.layout.pic_check, mainLayout, false);
RelativeLayout inflatedLayout = (RelativeLayout) findViewById(R.id.inflated);
ImageView iv= (ImageView)findViewById(R.id.imgv);
mainLayout.addView(inflatedLayout);
inflatedLayout.addView(iv);
iv.setImageBitmap(bitmap);//here i get NPE
}
我们将不胜感激
【问题讨论】:
标签:
android
nullpointerexception
android-imageview
android-inflate
【解决方案1】:
public void onDescriptionClick(){
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.camap);
View view = getLayoutInflater().inflate(R.layout.pic_check, mainLayout, false);
RelativeLayout inflatedLayout = (RelativeLayout) view.findViewById(R.id.inflated);
ImageView iv= (ImageView) view.findViewById(R.id.imgv);
mainLayout.addView(inflatedLayout);
inflatedLayout.addView(iv);
iv.setImageBitmap(bitmap);
}
【解决方案2】:
您的相对布局和图像视图在视图内
就这样吧……
public void onDescriptionClick(){
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.camap);
View view = getLayoutInflater().inflate(R.layout.pic_check, mainLayout, false);
RelativeLayout inflatedLayout = (RelativeLayout) view.findViewById(R.id.inflated);
ImageView iv= (ImageView)view.findViewById(R.id.imgv);mainLayout.addView(inflatedLayout);
inflatedLayout.addView(iv);
iv.setImageBitmap(bitmap);
mainLayout.addView(inflatedLayout);
}
【解决方案3】:
您有 NPE,因为您正在调用 findViewById(R.id.imgv),而 ImageView 尚未添加到您的“活动布局”,您必须调用 @987654323 @ 来自 "new inflated" 视图,否则它将返回一个空对象。
muruga5000 的回答是对的,但是代码有点乱。这是我的建议:
public void onDescriptionClick(){
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.camap);
View inflatedView = getLayoutInflater().inflate(R.layout.pic_check, mainLayout, false);
ImageView iv= (ImageView) inflatedView.findViewById(R.id.imgv);
iv.setImageBitmap(bitmap);
mainLayout.addView(inflatedView);
}