如何在Class中调用Toast?

How to call a Toast in the Class?

我的项目结构如下: Activity - 片段 - Class

问题:在Class中根据某些条件显示一个Toast

问题:我无法通过 getActivity()

从 class 调用上下文

如何解决最好?创建一些 Public class 或变量?

只需将 Context 发送给您的 class 构造函数。 像这样:

private Context context;

public MyClass(Context ctx) {
context = ctx;
}

然后用它来祝酒。

可以在Activityclass中调用Toast如下-

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(context, text, duration);
toast.show();

要在 Fragment 或另一个 class 中显示,您必须在 Fragment 的构造函数或特定的 class.Eg、[=13= 中传递 Activity 或上下文的引用]

Fragment fragment = new Fragment(activity);

在片段中 Class -

Class MyFragment extends Fragment{
     private Activity mActivity;

     MyFragment(Activity activity){
         mActivity = activity;
     }

     void showToast(){
         Toast.makeText(mActivity, text, duration);
     }

}

在没有太多上下文的情况下,我建议从 Activity 以外的 class 触发 Toast 消息的唯一方法是使用 Listener 接口:

public class Unknown {

    public interface UnknownListener {

        void displayMessage(CharSequence message);

    }

    private UnknownListener mUnknownListener;

    private final String mToastMessage = "Unknown message";

    public Unknown() {}

    public void setUnknownListener(UnknownListener listener) {
        mUnknownListener = listener;
    }

    private void doSomething() {
        if(mUnknownListener != null) {
            mUnknownListener.displayMessage(mToastMessage);
        }
    }

}

然后在您的 Activity 中实现接口,确保在相应的生命周期方法中删除引用:

public class MainActivity extends AppCompatActivity implements Unknown.UnknownListener {

    private Unknown mUnknown;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mUnknown = new Unknown();
        mUnknown.setUnknownListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnknown.setUnknownListener(null);
    }

    @Override
    public void displayMessage(CharSequence message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

}