Dynamically set custom AlertDialog content

时间秒杀一切 提交于 2019-12-22 08:16:27

问题


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



来源:https://stackoverflow.com/questions/9337344/dynamically-set-custom-alertdialog-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!