2012-03-18 51 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。