2012-12-30 30 views
6

我能夠使用此代碼的Android定製的祝酒詞

LayoutInflater inflater = getLayoutInflater(); 

    View layout = inflater.inflate(R.layout.custom_toast_layout, (ViewGroup)findViewById(R.id.custom_toast)); 

    TextView text = (TextView) layout.findViewById(R.id.toast_tv); 
    text.setText("Hello! This is a custom toast!"); 

    Toast toast = new Toast(getApplicationContext());  
    toast.setDuration(Toast.LENGTH_LONG); 
    toast.setView(layout); 
    toast.show(); 

然而,由於我不明白的LayoutInflater目的是爲了使自定義的敬酒,我修改了代碼,這...

Toast toast = new Toast(getApplicationContext()); 
    toast.setView(findViewById(R.id.custom_toast)); 
    toast.setDuration(Toast.LENGTH_SHORT); 
    toast.show(); 

我得到RuntimeException說「setView必須被調用」..

  • 爲什麼我不能將視圖分配給烤麪包而不使用LayoutInflater

  • LayoutInflater的目的通常是什麼,以便我可以將此體驗應用於其他自定義視圖?

編輯: 我正在使用onListItemClick()接口方法..內容設置之後,這些代碼..

+0

我認爲一個很好的問題是「LayoutInflater在內部做什麼」? – Behnam

回答

2

你的問題有你的答案,每個自定義視圖應該先膨脹,這就是原因您的修改後的代碼出現錯誤。

+0

如果我從xml分配一個Button給java,findViewById可以正常工作......我沒有在那裏使用任何inflater ..爲什麼在這裏使用它?是否因爲'setContentView'已經使用過一次,並且任何進一步的內容更改都應該來自佈局膨脹**? – BLOB

+0

,因爲吐司是自定義&按鈕不(默認)。與XML你可以分配/更改按鈕的某些屬性。 –

1
LayoutInflater inflater = getLayoutInflater(); 
View layout = inflater.inflate(R.layout.custom_toast, 
           (ViewGroup) findViewById(R.id.toast_layout_root)); 

TextView text = (TextView) layout.findViewById(R.id.text); 
text.setText("This is a custom toast"); 

Toast toast = new Toast(getApplicationContext()); 
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); 
toast.setDuration(Toast.LENGTH_LONG); 
toast.setView(layout); 
toast.show(); 

這就是你也做了,而且它是完全正確的代碼,你有你的答案, 因爲我們必須首先使用infalte自定義視圖指定自定義視圖。

謝謝