0
我的代碼:對話框投擲「無法添加窗口 - 令牌null不是一個應用程序」
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NoticeBoard.init(MainActivity.this);
NoticeBoard.getInstance().setButton();
setContentView(NoticeBoard.getInstance());
}
}
public class NoticeBoard extends ImageView {
private static NoticeBoard instance = null;
private static Paint paint;
protected Context mContext;
private static WindowManager mWindowManager;
public NoticeBoard(Context context, AttributeSet attrs) {
super(context, attrs);
}
public static NoticeBoard getInstance() {
return instance;
}
public static void init(Context context) {
instance = new NoticeBoard(context);
instance.setImageResource(R.drawable.ic_launcher);
instance.invalidate();
}
public NoticeBoard(Context context) {
super(context);
mWindowManager = (WindowManager) getContext().getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
mContext = context;
setBackgroundColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint = new Paint(Paint.LINEAR_TEXT_FLAG);
paint.setColor(Color.GRAY);
paint.setTextSize(12.0F);
canvas.drawText("Hello World", 100, 200, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
public void setButton() {
Activity a =(Activity) mContext;
ImageButton btn = new ImageButton(a);
btn.setBackgroundResource(R.drawable.ic_launcher);
android.view.WindowManager.LayoutParams paramsSplit = new android.view.WindowManager.LayoutParams();
paramsSplit.width=2;
paramsSplit.height=2;
instance.mWindowManager.addView(btn, paramsSplit);
}
}
我試圖找到答案,我改變getApplicationContext()來MainActivity.this,並改變上下文?(活動)上下文,但它仍然不能正常工作有什麼不妥的地方 Ps.I'm中國人,我的英語不太好感謝您的幫助
@EJK我將getApplicationContext()更改爲MainActivity.this,但仍然不起作用。 –
這只是一個猜測,但如何更改「mWindowManager =(WindowManager)getContext()。getApplicationContext()。getSystemService(Context.WINDOW_SERVICE);」to「mWindowManager =(WindowManager)getContext()。getSystemService(Context.WINDOW_SERVICE) ;「 – EJK
要澄清我的上述評論:只需嘗試刪除該行的」getApplicationContext()「部分即可。 – EJK