2012-06-26 20 views
0

所以我用this教程來創建一個自定義的烤麪包,它會顯示一個圖像。如何訪問未運行的視圖?

現在我想要做的是能夠傳遞圖像資源並告訴我的吐司方法來顯示該圖像。

所以我有這樣的:

private void callToast(int image_resource) 
{    
    LayoutInflater inflater = getLayoutInflater(); 
    View v = inflater.inflate(R.layout.mycustomtoast, (ViewGroup) findViewById(R.id.toast_layout)); 

    /*set the image*/   
    ImageView iv = (ImageView)findViewById(R.id.toast_iv); 
    iv.setImageResource(image_resource); 

    Toast t = new Toast(this); 
    t.setView(v); 
    t.setGravity(Gravity.CENTER,0,0); 

    t.show(); 
} 

現在findViewById返回null ......我理解,因爲這是下的XML沒有被使用?

如何更改定製烤麪包圖片視圖的來源?

回答

2

在這裏,你忘了查看refrence v

ImageView iv = (ImageView)v.findViewById(R.id.toast_iv); 

解決方案

Toast t = new Toast(this); 
t.setView(v); 

ImageView iv = (ImageView)v.findViewById(R.id.toast_iv); 
iv.setImageResource(image_resource); 

t.setGravity(Gravity.CENTER,0,0); 
+0

感謝。 我想我對findViewById的使用有點困惑 - 因爲你通常可以單獨使用它(不附加到視圖對象)。當你自己使用它時,它只是搜索當前活動的xml? – dwjohnston