在Fragment中添加DataPicker TimePicker以及NotificationManager的使用
在onCreateView中实例化控件
View view = inflater.inflate(R.layout.data, container,false);
tv_date=(TextView)view.findViewById(R.id.tv_date);
tv_time=(TextView)view.findViewById(R.id.tv_time);
date_picker=(DatePicker)view.findViewById(R.id.date);
time_picker=(TimePicker)view.findViewById(R.id.time);
view.findViewById(R.id.button1).setOnClickListener(this);
view.findViewById(R.id.button2).setOnClickListener(this);
changetext();
manager =(NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
如果在onCreate描绘控件 会报空指针错误
在fragment的生命周期中会先执行onCreate 后执行onCreateView
所以要在onCreateView中添加自定义方法changetext() 来控制 UI组件
Changetext()
private void changetext() {
//获取当前的年月日时分信息
Calendar c=Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DAY_OF_MONTH);
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
tv_date.setText("现在日期:"+year+"-"+(month+1)+"-"+day);
tv_time.setText("现在时间:"+hour+":"+minute);
date_picker.init(year, month, day, new OnDateChangedListener() {
//监听日期的改变
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
tv_date.setText("现在日期:"+year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
}
});
//设置时间为24小时制
time_picker.setIs24HourView(true);
time_picker.setOnTimeChangedListener(new OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
tv_time.setText("现在时间:"+hourOfDay+":"+minute);
}
});
}
NotificationManager的使用
首先实现控制类
private NotificationManager manager;//通知控制类
因为其用的为系统方法 所以要添加
manager =(NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
由于在fragment这种视图中所以写法不同
通过Button点击事件控制方法的调用
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
sendNotification();
break;
case R.id.button2:
manager.cancel(notification_ID);
b}
}
```
<div class="se-preview-section-delimiter"></div>
这里写代码片
“`
private void sendNotification() {
// TODO Auto-generated method stub
Builder builder = new Notification.Builder(getActivity());
builder.setSmallIcon(R.drawable.ic_launcher);//设置图标
builder.setTicker("hello");//手机状态栏的提示;
builder.setWhen(System.currentTimeMillis());//设置时间
builder.setContentTitle("通知栏通知");//设置标题
builder.setContentText("我来自NotificationDemo");//设置通知内容
// builder.setContentIntent(pintent);//点击后的意图
// builder.setDefaults(Notification.DEFAULT_SOUND);//设置提示声音
// builder.setDefaults(Notification.DEFAULT_LIGHTS);//设置指示灯
// builder.setDefaults(Notification.DEFAULT_VIBRATE);//设置震动
builder.setDefaults(Notification.DEFAULT_ALL);//设置震动
Notification notification = builder.build();//4.1以上
//builder.getNotification();
manager.notify(notification_ID, notification);
}