先給出自定義的ToastUtil類:java
package com.example.edm; import android.content.Context; import android.widget.Toast; public class ToastUtil { public static Toast toast; public static void showMessage(Context context, String message) { if(toast==null) { toast= Toast.makeText(context,message,Toast.LENGTH_LONG); }else { toast.setText(message); } toast.show(); } }
假設我在B類中須要使用ToastUtil在A類中顯示信息,不能直接使用:android
ToastUtil.showMessage(A.class, message)
而是應該在B中定義一個Context變量,在A中生成B時將A.this傳進去。 好比說A(JWLoginActivity)爲登陸界面,B(ConnectJWGL)爲具體的登陸實現類,在A中調用:函數
ConnectJWGL connectJWGL = new ConnectJWGL(id, password1, password2, JWLoginActivity.this);
能夠看出,咱們須要把自身JWLoginActivity.this傳進去,那麼在B也就是ConnectJWGL中,咱們定義它的構造函數爲:this
public ConnectJWGL(String stuNum, String in_Password, String jw_Password, Context mContext) throws Exception { this.stuNum = stuNum; this.in_Password = in_Password; this.jw_Password = jw_Password; this.mContext = mContext; }
其中mContext是B中本身定義的變量,那麼這個時候就能夠在B中調用:spa
ToastUtil.showMessage(mContext, "登陸成功!");