public class MyFragment4 extends Fragment {
private Button btn;
public MyFragment4() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_content4, container, false);
btn = (Button) view.findViewById(R.id.send_not);
btn.setText("发送通知");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e("HEHE", "哈哈");
NotificationManager notificationManager =
(NotificationManager)(MyFragment4.this.getContext().getSystemService(Context.NOTIFICATION_SERVICE));
Notification.Builder mBuilder = new Notification.Builder(this); // 错误在this这里
mBuilder.setContentTitle("叶良辰") //标题
.setContentText("我有一百种方法让你呆不下去~") //内容
.setSubText("——记住我叫叶良辰") //内容下面的一小段文字
.setTicker("收到叶良辰发送过来的信息~") //收到信息后状态栏显示的文字信息
.setWhen(System.currentTimeMillis()) //设置通知时间
.setSmallIcon(R.mipmap.ic_launcher) //设置小图标
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE) //设置默认的三色灯与振动器
.setAutoCancel(true); //设置点击后取消Notification
Notification notification = mBuilder.build();
notificationManager.notify(1, notification);
}
});
Log.e("HEHE", "4日狗");
return view;
}
}
运行报错:错误: 不兼容的类型: <匿名OnClickListener>无法转换为Context
传的明明是个Fragment,当然转不了,调Fragment的getContext方法获取
将:
Notification.Builder mBuilder = new Notification.Builder(this); // 错误在this这里
替换为:
Notification.Builder mBuilder = new Notification.Builder(MyFragment4.this.getContext());