2009-12-21 102 views
0

我想創建一個幫助器類來顯示我的android應用程序中的Toasts,如下所示。android吐司和查看幫助

公共類ToastHelper {

final static Toast toastAlert(String msg) { 
    LayoutInflater inflater = LayoutInflater.from(Main.self.getApplicationContext()); 
    View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root)); 

    TextView tv = (TextView)layout.findViewById(R.id.toast_text); 
    tv.setText(msg); 

    Toast toast = new Toast(Main.self.getApplicationContext()); 
    toast.setDuration(Toast.LENGTH_SHORT); 
    toast.setView(layout); 
    return toast; 
} 

}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
      android:id="@+id/toast_layout_root" 
      android:orientation="horizontal" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:padding="10dip" 
      android:background="#FFF" 
      > 
<TextView android:id="@+id/toast_text" 
      android:layout_width="wrap_content" 
      android:layout_height="fill_parent" 
      android:textColor="#000" 
      /> 

我的代碼是基於這個例子:http://developer.android.com/guide/topics/ui/notifiers/toasts.html

我的問題是,當我嘗試膨脹該視圖,我不能從acti的視圖調用findViewById vity我打電話給toastAlert英寸有沒有一種方法可以訪問該視圖?

回答

1

我唯一的想法是將一個View傳遞給該方法。它不會那麼糟糕,全部是這樣的:

class.toastAlert(this, "My Toast"); 
+0

我記得很多幫助函數最終需要一個視圖或上下文,最簡單的處理方法就是傳遞它。 – 2009-12-21 21:16:33

0

我用這個來獲得LayoutInflator

LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE); 

我不知道這是否會幫助或沒有。