jlim
jlim

Reputation: 811

android Toast and View help

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?

Upvotes: 0

Views: 991

Answers (2)

Ryan Alford
Ryan Alford

Reputation: 7594

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.

Upvotes: 0

CaseyB
CaseyB

Reputation: 25058

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");

Upvotes: 1

Related Questions