2012-12-30 13 views
6

मैं इस कोड का उपयोगएंड्रॉयड कस्टम टोस्ट

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

मुझे लगता है कि एक अच्छा सवाल "लेआउट इन्फ्लेटर आंतरिक रूप से क्या करता है"? – Behnam

उत्तर

2

आपका प्रश्न आपका जवाब, हर कस्टम दृश्य पहले बढ़ चाहिए, कि कारण नहीं है है आपको अपने संशोधित कोड में एक त्रुटि मिली है।

+0

अगर मैं xml से जावा को बटन सौंप रहा हूं, तो findViewById ठीक काम करता है ... मैं वहां किसी भी inflater का उपयोग नहीं करता .. इसका उपयोग क्यों करें? ऐसा इसलिए है क्योंकि 'setContentView' पहले से ही एक बार उपयोग किया जा रहा है और कोई और सामग्री परिवर्तन ** लेआउट inflating ** से होना चाहिए? – BLOB

+0

क्योंकि टोस्ट कस्टम है और बटन नहीं है (एंड्रॉइड डिफ़ॉल्ट)। एक्सएमएल के साथ आप बटन की कुछ संपत्ति असाइन/बदल सकते हैं। –

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 उपयोग करने के लिए असाइन कस्टम दृश्य के लिए की है।

धन्यवाद