2010-09-15 100 views
1

好的,所以我想有一个自定义对话框,但我无法弄清楚我的生活如何使它在调用函数时出现。显示自定义对话框

public void addHomework() { 
    final Dialog alert = new Dialog(this); 

    alert.setTitle("Add Homework"); 

    alert.setContentView(R.layout.homework_item_entry); 

    Button add_button = (Button) findViewById(R.id.add_homework_button); 
    Button cancel_button = (Button) findViewById(R.id.cancel_homework_button); 

    add_button.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      Toast.makeText(ClassHomeworkList.this, "Adding homework", Toast.LENGTH_SHORT).show(); 
     } 
    }); 

    cancel_button.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
      alert.dismiss(); 
     } 
    }); 

    alert.show(); 
} 

我该怎么办?

+0

现在会发生什么? – 2010-09-15 20:34:33

+0

一点都没有,没有出现。 – Chiggins 2010-09-15 21:00:18

+0

你应该真的使用onCreateDialog来代替,它有助于处理像旋转屏幕时恢复的事情。只要基本上移动你的构建器代码,然后返回它处理剩下的对话框。 – schwiz 2010-09-15 21:01:51

回答

1

我觉得你有你的两个按钮不能被相应的ID这样发现问题(如你正在努力寻找他们在您的主要活动,但他们都在布局对话框)

Button add_button = (Button) findViewById(R.id.add_homework_button); 
Button cancel_button = (Button) findViewById(R.id.cancel_homework_button); 

但不是需要做的:

Button add_button = (Button) alert.findViewById(R.id.add_homework_button); 
Button cancel_button = (Button) alert.findViewById(R.id.cancel_homework_button); 
0
LayoutInflater factory = LayoutInflater.from(this); 
View view = factory.inflate(R.layout.dialog, null); 

//the id is your root layout 
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout); 
alert.setContentView(layout); 
4

我知道这是一个古老的线程,但即使阅读了Android文档后,也没有明显的对我,你应该重写你的活动的onCreateDialog(int)方法如何使用标准Dialog类显示自定义对话框。基本上你可以拨打:

this.showDialog(MANAGE_PASSWORD); // MANAGE_PASSWORD static final int 

你的活动。然后实例在onCreateDialog方法定制对话框:

protected Dialog onCreateDialog(int id) { 
     Dialog dialog; 
     switch(id) { 
     case MANAGE_PASSWORD: 
      dialog= getInstancePasswordDialog(); 
      break; 
     case DIALOG_ABOUT: 
      // do the work to define the About Dialog 
      dialog= getInstanceAlertDialog(); // called "the first time" 
      break; 
     default: 
      dialog = null; 
     } 
     return dialog; 
    } 

该代码实例化对话是在getInstancePasswordDialog()。这是code sample