图像不会在充气的ImageView上显示

时间:2016-01-11 08:18:10

标签: android nullpointerexception android-imageview android-inflate

我试图在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
}

帮助将不胜感激

3 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分: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);
mainLayout.addView(inflatedLayout);
}

答案 2 :(得分:0)

您拥有 NPE ,因为您正在调用findViewById(R.id.imgv)ImageView尚未添加到您的"活动布局&#34 ; ,您必须从"新的" 视图中调用findViewById,否则它将返回一个空对象。

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

}