创建AlertDialog的问题

时间:2011-08-11 05:30:36

标签: android android-alertdialog

我似乎遇到了创建AlertDialog的问题。我想要做的是创建一个自定义AlertDialog,单击特定的RadioButton时弹出。这是我的相关代码:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        m_Minutes = -1;
        m_this=this;

        String prefName = getString(R.string.prefsfile);
        SharedPreferences settings = getSharedPreferences(prefName, 0);
        String defaultTextBackMessage = settings.getString("textBackMessage", getString(R.string.defaultTextBackMessage));
        EditText txtMessage = (EditText)findViewById(R.id.editText1);
        txtMessage.setText(defaultTextBackMessage);

        final Button button = (Button)findViewById(R.id.button1);
        final RadioButton manualButton = (RadioButton)findViewById(R.id.radio0);
        final RadioButton button15 = (RadioButton)findViewById(R.id.radio1);
        final RadioButton button30 = (RadioButton)findViewById(R.id.radio2);
        final RadioButton customButton = (RadioButton)findViewById(R.id.radio3);

        manualButton.setChecked(true);
        customButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Context c = v.getContext();
                LayoutInflater factory = LayoutInflater.from(v.getContext());
                final View minuteEntryView = factory.inflate(R.layout.customtime, null);
                AlertDialog ad = AlertDialog.Builder(c).create(); // this is the trouble line
            }
        });

我在AlertDialog ad = AlertDialog.Builder(c).create();行收到错误。我得到的错误是The Method Builder(Context) is undefined for the type AlertDialog。但显然,Google API Docs确实有一个Builder构造函数。我做错了什么?

2 个答案:

答案 0 :(得分:8)

你不应该这样说......

AlertDialog ad = new AlertDialog.Builder(c).create();

你忘记了new keyWord .. 正如你可以清楚地看到的那样,它没有找到Method,这意味着你以通常的方式调用它的构造函数,但是你调用方法的方式。

答案 1 :(得分:0)

您需要在Activity中覆盖onCreateDialog(int id)方法。在该方法中,您应该创建Dialog对象,并且从RadioButton的onClick事件中,您应该使用showDialog(id)方法调用该对话框。

见下面的代码:

@Override
protected Dialog onCreateDialog(int id) 
{
    // TODO Auto-generated method stub

    AlertDialog dialog = null;
    AlertDialog.Builder builder = null;

    builder = new AlertDialog.Builder(this);

    switch(id) 
    {
    case USERNAME_PASSWORD_EMPTY:

        builder.setMessage("Please Enter Username and Password.");
        builder.setCancelable(false);

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
        {
            public void onClick(DialogInterface dialog, int id) 
            {
                //Do what you want to do when user clicks OK button of dialog
            }
        });

        dialog = builder.create();

    break;
    }

    return dialog;
}

您必须使用showDialog(id)方法调用此对话框,如下所示:

showDialog(USERNAME_PASSWORD_EMPTY);