图像不会显示在膨胀的 ImageView 上

image won't show on inflated ImageView

我正在尝试对我在 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
}

帮助将不胜感激

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);
}

您有 NPE 因为您正在调用 findViewById(R.id.imgv)ImageView 尚未添加到您的 "activity layout",您必须从 "new inflated" 视图调用 findViewById,否则它将 return 一个空对象。

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);

}

你的相对布局和imageview在视图里面 就这样做...

     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);
}