2012-10-24 29 views
0

我已經搜索並搜索了這個內容,但不幸的是我沒有找到任何關於如何在自定義對話框上重複使用以前充氣的視圖的有用信息。防止每次在自定義對話框上充氣

這是我試過(他們沒有工作)

方法1:

保持我alertdialog建設者全球和內onCreate()做什麼,我需要:

private AlertDialog.Builder dialog; 

public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     dialog = new AlertDialog.Builder(this); 
     detailView = getLayoutInflater().inflate(R.layout.detail, null); 
     TextView textview1 = (TextView)detailView.findViewById(R.id.lblName); 
     TextView textview2 = (TextView)detailView.findViewById(R.id.lblSubtitle); 

     textview1.setText("Test1"); 
     textview2.setText("Test2"); 
     dialog.setView(detailView); 
     dialog.create(); 

    btnSearch = (ImageView)findViewById(R.id.btnSearch); 
    btnSearch.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View v) { 
      dialog.show(); 
     } 
    }); 
    } 

然後只在需要時顯示它:dialog.show();

沒有工作,LogCat輸出T:

Uncaught handler: thread main exiting due to uncaught exception 
java.lang.IllegalStateException: The specified child already has a parent. 
You must call removeView() on the child's parent first. 

方法2:

onCreate()剛剛膨脹的佈局,並在單擊事件:

dialog = new AlertDialog.Builder(this); 
    TextView textview1 = (TextView)detailView.findViewById(R.id.lblName); 
    TextView textview2 = (TextView)detailView.findViewById(R.id.lblSubtitle); 
    textview1.setText("Test1"); 
    textview2.setText("Test2"); 
    dialog.setView(detailView); 
    dialog.create(); 

但它墜毀給予同樣的錯誤輸出。

當然,我已經閱讀了輸出結果,並試圖找到父母,所以我猜父母會是對話框本身,但它沒有任何方法來刪除視圖,所以我不知道是什麼去做。

還有沒有辦法重用textview引用?

(我知道它的編碼不,只是想獲得它的工作,我會得到它正確地重構。

+0

您是否特別關注它是一個提醒對話框?因爲它看起來並不像你希望它是可交互的,在這種情況下,你可以繼續使用自定義的「Toast dialog = new Toast(Activity)」來實現你想要的結果 – gaara87

+0

它根本不會是交互式的,它只會顯示信息,但吐司將不夠用,因爲我將顯示覆雜的控件(圖像視圖,列表)。 – Areks

+0

也使用inflate()中的第二個參數可能也有幫助 – gaara87

回答

0

已經解決了這個問題:

的問題如下:

我試圖顯示AlertDialog.Builder而不是AlertDialog。當我宣佈它爲dialog時,我不知道我在想什麼。

我剛剛聲明瞭一個AlertDialog並指定了builder.create()的結果,現在它的工作原理就是一次充氣。

非常感謝你們,特別是@Laurence Dawson,他的回答讓我意識到我的代碼是錯誤的。

1

當您取消或關閉該對話框,您需要刪除的膨脹視圖。下面的代碼呢這樣的:

dialog.setOnDismissListener(new OnDismissListener() { 
    @Override 
    public void onDismiss(DialogInterface dialog) { 
    try{ 
     ((FrameLayout)detailView.getParent()).removeView(detailView); 
    }catch(Exception e){ 
     //todo handle the case detailView doesn't have a parent 
    } 
    } 
}); 

然後您可以將您的DetailView重新添加到一個新的對話框

+0

這不是答案,但我喜歡你,因爲你的回答讓我意識到我沒有正確地命名我的對象。所以這完全有用。 因爲我試圖在我的「對話框」上設置OnDismissListener,它實際上是一個AlertDialog.Builder。 非常感謝! – Areks

+0

我會將其標記爲正確,因爲它可以幫助其他人看到如何刪除對話框的自定義視圖。 – Ljdawson