自定义吐司:findViewById(R.id.toast)出错

时间:2012-09-28 17:03:02

标签: android toast

我正在尝试制作自定义Toast但我收到以下错误:

  

无法找到符号   (ViewGroup)findViewById(R.id.toast_root));

同时在代码的其他行中可以看到findViewById()。 我的错是什么?

public class MyCustomToast extends Toast {


public MyCustomToast(Context context){
    super(context);
}

public static Toast customToast(Context context, CharSequence text, int duration) {



    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) findViewById(R.id.toast_root));

    ImageView image = (ImageView) layout.findViewById(R.id.toast_image);
    image.setImageResource(R.drawable.skipper_toast);

    TextView text_toast = (TextView) layout.findViewById(R.id.toast_text);
    text_toast.setText(text);

    Toast toast = new Toast(context);

    toast.setGravity(Gravity.TOP, 0, 0);
    toast.setDuration(duration);
    toast.setView(layout);
    toast.show();

    return toast;
}
}

1 个答案:

答案 0 :(得分:1)

以下是您应该如何更改代码:

public class MyCustomToast extends Toast {


public MyCustomToast(Context context){
    super(context);
}

public static Toast customToast(Activity activity, CharSequence text, int duration) {



    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View layout = inflater.inflate(R.layout.toast_layout, (ViewGroup) activity.findViewById(R.id.toast_root));

    ImageView image = (ImageView) layout.findViewById(R.id.toast_image);
    image.setImageResource(R.drawable.skipper_toast);

    TextView text_toast = (TextView) layout.findViewById(R.id.toast_text);
    text_toast.setText(text);

    Toast toast = new Toast(context);

    toast.setGravity(Gravity.TOP, 0, 0);
    toast.setDuration(duration);
    toast.setView(layout);
    toast.show();

    return toast;
}
}

希望这有帮助。