2011-08-11 26 views
2

我似乎遇到了創建AlertDialog的問題。我試圖做的是創建一個自定義的AlertDialog,當點擊一個特定的RadioButton時彈出。這裏是我的相關代碼:創建AlertDialog時出現問題

@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構造函數。我究竟做錯了什麼?

+0

您能告訴我們錯誤logcat嗎? –

+0

@Suri - 我得到一個編譯錯誤,而不是運行時錯誤 – Icemanind

+0

我面臨同樣的問題,我不能相信我忘了「新」。我需要一個休息的男人! – Ishaan

回答

8

should't你說這......

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

你忘了new keyWord .. 正如你可以清楚地看到,其說法沒有找到方法,whic h意味着你以通常的方式調用它的構造函數,但是以你調用方法的方式。

+0

哈哈這是我的問題。謝謝ntc! – Icemanind

0

您需要重寫Activity中的onCreateDialog(int id)方法。在該方法中,您應創建Dialog對象,並使用showDialog(id)方法從RadioButton的onClick事件中調用對話框。

請參見下面的代碼:

@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);