Dynamically set custom AlertDialog content

2019-05-04 12:51发布

问题:

I have a custom dialog that I set up as a function:

public void customDialog(Bitmap bm, String title){
    TextView dialogtext = (TextView)findViewById(R.id.layout_root);
    //For above also tried r.id.popup which is the containing file for the layout
    ImageView dialogimage = (ImageView)findViewById(R.id.popupimage); 

    dialogtext.setText(title);
    dialogimage.setImageBitmap(bm);

    LayoutInflater inflater = getLayoutInflater();
    View layout = inflater.inflate(R.layout.popup, (ViewGroup) findViewById(R.id.layout_root));
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(layout);
    builder.show();
}

The dialog fails whenever I try to set the XML fields dynamically with a Null Pointer Exception. I'm stumped, any ideas? Do I have to add something to the manifest for a custom dialog?

回答1:

do this first:

View layout = inflater.inflate(R.layout.popup, (ViewGroup) findViewById(R.id.layout_root));

Then, after you define layout, do this:

ImageView dialogimage = (ImageView) layout.findViewById(R.id.popupimage);

Call findViewByID() on the new layout you created, not on the parent content view.

So two changes: Ordering, and layout.findView not findView