允许从其他类访问toast

时间:2011-03-09 22:23:57

标签: java android

我正在尝试使用另一个类的吐司。

在第1课我有吐司方法:

public static void textToast(String textToDisplay) 
{
    Context context = getApplicationContext();
    CharSequence text = textToDisplay;
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);
    toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER, 50, 50);
    toast.show();
}

我试图从另一个类调用这个toast,但是当我将该方法设为静态时,它表示无法对此方法进行静态引用getApplicationContext().

我使用class2.textToast("");

访问它

对此有任何建议将不胜感激。感谢

2 个答案:

答案 0 :(得分:4)

如果您想提供一个对不同的上下文(例如活动)有效的方法,请将此上下文作为参数传递。

public static void textToast(String textToDisplay, Context context)  { ... }

如果要从嵌套的内部类中调用此方法(通常就是这种情况),可以使用this作为上下文

public void textToast(String textToDisplay) {
    ...
    Toast toast = Toast.makeText(OuterClass.this, text, duration);
    ...
}

(或在外部类中实现textToast并通过嵌套内部类中的OuterClass.this.textToast调用它)

答案 1 :(得分:0)

public void FlesmynToast(Activity fActivity, String fMessage) {
    LayoutInflater fInflater = fActivity.getLayoutInflater();
    View fView = fInflater.inflate(R.layout.custom_toast (ViewGroup) fActivity.findViewById(R.id.custom_toast_layout_id));

    ImageView image = (ImageView) fView.findViewById(R.id.image);
    image.setImageResource(R.drawable.ic_launcher);

    TextView fText = (TextView) fView.findViewById(R.id.text);
    fText.setText(fMessage);

        // Toast...
    Toast fToast = new Toast(fActivity.getApplicationContext());
    fToast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    fToast.setDuration(Toast.LENGTH_LONG);
    fToast.setView(fView);
    fToast.show();
}
相关问题