1. 程式人生 > >Toast--報錯

Toast--報錯

attrs ttr pub app rri 應該 err ket tex

Toast的makeText()方法報錯
帖上一代碼,用Toast來簡單處理回調機制.但是Toast的makeText()方法老報錯:
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.Toast;

public class MyButton extends Button {


public MyButton(Context context, AttributeSet attrs) {


super(context, attrs);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
//就是這裏了

Toast toast=Toast.makeText(MyButton.this, "the callBack test", 5000);
toast.show();
return true;
}
}
報錯信息:

The method makeText(Context, CharSequence, int) in the type Toast is not applicable for the arguments (MyButton, String, int)



------解決方案--------------------
public class MyButton extends Button {

private Context mContext;

public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}

Toast toast=Toast.makeText(mContext, "the callBack test", 5000);
toast.show();
------解決方案--------------------
第一個參數,使用 getContext() 或者 getApplicationContext()

第三個參數也不正確,應該是 Toast.makeText(getContext(), "the callBack test", Toast.LENGTH_LONG).show();

Toast--報錯