2012-03-18 24 views
3

我有一個非常簡單的對話定義爲:是什麼讓對話框可以顯示?

import android.app.AlertDialog; 
import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 

public class MyDialog{ 

    private String promptReply = null; // local variable to return the prompt reply value 

    public String showAlert(String ignored, Context ctx) 
    { 
    LayoutInflater li = LayoutInflater.from(ctx); 
    View view = li.inflate(R.layout.promptdialog, null); 

    AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
    builder.setTitle("Dialog Title"); 
    builder.setView(view); 

    builder.setPositiveButton("OK", (myActivity)ctx); 
    builder.setNegativeButton("Cancel", (myActivity)ctx); 

    AlertDialog ad = builder.create(); 

    ad.show(); 
    return "dummystring";  
    } 
} 

,當我嘗試呼籲setContentView()該活動的主要佈局後onCreate()來顯示它的對話框根本不顯示:

MyDialog dialog = new MyDialog(); 
dialog.showAlert("Why isn't this shown???", this); 

另一方面,如果我在之前將相同的確切電話號碼放在setContentView()之前作爲活動的主要佈局,則對話框顯示得很好。

我的問題是爲什麼?

爲什麼訂單在這種情況下至關重要?

我錯過了什麼?

回答

2

在你的代碼膨脹視圖,使用這樣的:

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

其中layout_root是您的自定義對話框的頂層佈局的ID。

相關問題