如何在课堂上致电Toast?

时间:2016-10-12 20:03:11

标签: android android-toast public-method

我的项目结构如下: 活动 - 片段 - 类

问题:在类中根据某些条件显示Toast

问题:我无法通过getActivity()

从类中调用Context

如何以最佳方式解决问题?创建一些公共类或变量?

3 个答案:

答案 0 :(得分:1)

如果没有太多上下文,我建议从Toast以外的类触发Activity消息的唯一方法是使用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();
    }

}

答案 1 :(得分:0)

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

private Context context;

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

然后用它来表示敬酒。

答案 2 :(得分:0)

您可以在Activity类中调用Toast,如下所示 -

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

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

要在Fragment或其他类中显示,您必须在Fragment的构造函数或特定的类中传递Activity或Context的引用.Eg,

Fragment fragment = new Fragment(activity);

在片段类中 -

Class MyFragment extends Fragment{
     private Activity mActivity;

     MyFragment(Activity activity){
         mActivity = activity;
     }

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

}