tags:

views:

164

answers:

2

I am trying to create a Helper class to display Toasts in my android app, as follows.

public class 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"
          />

My code is based on the example at: http://developer.android.com/guide/topics/ui/notifiers/toasts.html

My problem is, when I try to inflate the view, I can't call findViewById without the View from the activity I am calling toastAlert in. Is there a way I can access that view?

+1  A: 

My only thought would be to pass a View into the method. It wouldn't be so bad, the all would look like this:

class.toastAlert(this, "My Toast");
CaseyB
I recall a lot of helper functions end up needing a View or a Context, and the easiest way to deal with that is to just pass it around.
Daniel Yankowsky
A: 

I use this to get the LayoutInflator

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

I don't know if that will help or not.

Eclipsed4utoo