繁体   English   中英

允许从另一个班级访问烤面包

[英]Allow toast to be accessible from another class

我正在尝试使用另一堂课的吐司。

在第1课中,我有toast方法:

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().进行静态引用getApplicationContext().

我通过使用class2.textToast("");访问它

任何建议,将不胜感激。 谢谢

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

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从嵌套内部类)

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM