Android - 从静态类显示对话框

时间:2012-03-07 21:55:48

标签: java android

我有一个简单的类,我想用它来显示一个Dialog消息:

public class Utils {

    static void ShowMessage(Context c, String DialogTitle, String MessageToDisplay, int LayoutResourceID, int ImageResourceID ){

        //Create new dialog.
        Dialog dialog = new Dialog(c);

        //Set the view to an existing xml layout.
        dialog.setContentView(LayoutResourceID);
        dialog.setTitle(DialogTitle);

        //Set textbox text and icon for dialog.
        TextView text = (TextView) dialog.findViewById(R.id.text);
        text.setText(MessageToDisplay);
        ImageView image = (ImageView)dialog.findViewById(R.id.image);
        image.setImageResource(ImageResourceID);

        //Show the dialog window.
        dialog.show();
    }
}

我试图在我的活动中,在按钮的OnClickListener事件中调用它,如下所示:

private OnClickListener btnSubmitIssueClick = new OnClickListener(){

    public void onClick(View v){
        //Check for valid Summary & Description.
        if(mSummaryEditText.getText().toString().trim().length() == 0){
            Utils.ShowMessage(getBaseContext(), "Submit Issue Error", getBaseContext().getString(R.string.ERROR_SummaryRequired),
                    R.layout.modal_dialog, R.drawable.warning);
            return;
        }else if(mDescriptionEditText.getText().toString().trim().length() == 0){
            Utils.ShowMessage(getBaseContext(), "Submit Issue Error", getBaseContext().getString(R.string.ERROR_DescriptionRequired),
                    R.layout.modal_dialog, R.drawable.warning);
            return;
        }
    }
};

但是当我运行它时,我收到了这个错误:

03-07 16:56:00.290: W/WindowManager(169): Attempted to add window with non-application token WindowToken{4162e780 token=null}.  Aborting.

关于我做错了什么的想法?

1 个答案:

答案 0 :(得分:1)

您将基本上下文作为用于创建对话框的上下文传递。这需要是托管对话框的活动的上下文。活动本身实际上是上下文对象,因此您只需传入对活动的引用。

以下SO问题here给出了更完整的解释。