动态设置自定义AlertDialog内容

时间:2012-02-18 00:32:10

标签: android android-alertdialog

我有一个自定义对话框,我将其设置为函数:

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

每当我尝试使用Null Pointer Exception动态设置XML字段时,对话框都会失败。我很难过,有什么想法吗?我是否必须在清单中添加一些自定义对话框?

1 个答案:

答案 0 :(得分:2)

首先执行此操作:

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

然后,在定义layout之后,执行以下操作:

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

在您创建的新布局上调用findViewByID(),而不是在父内容视图上调用。{/ p>

因此有两项变更:订购,layout.findView而非findView