2010-09-15 99 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