我的代码:
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,并将上下文更改为(Activity)Context,但它仍然无效。它有什么问题? 我是中国人,我的英语不是很好。谢谢你的帮助。
答案 0 :(得分:0)
在以下行中:
mWindowManager = (WindowManager) getContext().getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
删除对应用程序上下文的引用
mWindowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
活动的背景就足够了。