在时间选择器中的选定时间创建通知时,我做了所有事情,但是我无法将其传递给另一个活动中的textview。有人可以帮我弄这个吗?
点击“完成”按钮后,我想将时间值从SecondActivity
传递到textView
中名为textviewAlarm
的{{1}}。
HomeActivity
我希望我选择的时间显示在public class Second extends AppCompatActivity implements View.OnClickListener{
private int notificationId = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
// Set Onclick Listener.
findViewById(R.id.setBtn).setOnClickListener(this);
findViewById(R.id.cancelBtn).setOnClickListener(this);
}
@Override
public void onClick(View view) {
EditText editText = findViewById(R.id.editText);
TimePicker timePicker = findViewById(R.id.timePicker);
// Set notificationId & text.
Intent intent = new Intent(Second.this, AlarmReceiver.class);
intent.putExtra("notificationId", notificationId);
intent.putExtra("todo", editText.getText().toString());
// getBroadcast(context, requestCode, intent, flags)
PendingIntent alarmIntent = PendingIntent.getBroadcast(Second.this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
switch (view.getId()) {
case R.id.setBtn:
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
// Create time.
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, minute);
startTime.set(Calendar.SECOND, 0);
long alarmStartTime = startTime.getTimeInMillis();
// Set alarm.
// set(type, milliseconds, intent)
alarm.set(AlarmManager.RTC_WAKEUP, alarmStartTime, alarmIntent);
// Get TextView object which is used to show user pick date and time.
TextView textView = (TextView)findViewById(R.id.textViewAlarm);
StringBuffer strBuffer = new StringBuffer();
strBuffer.append("You selected date time : ");
strBuffer.append(this.notificationId);
textView.setText(strBuffer.toString());
break;
case R.id.cancelBtn:
alarm.cancel(alarmIntent);
Toast.makeText(this, "Canceled.", Toast.LENGTH_SHORT).show();
break;
}
}
}
的{{1}}中。
答案 0 :(得分:4)
您可以通过添加
从时间选择器中获取时间。timePicker.setOnTimeChangedListener( new TimePicker.onTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
time = String.valueOf(hourOfDay).toString() + ":" + String.valueOf(minute).toString();
}
}
当用户更改时间时,它将为变量分配时间,并按如下所示通过意图传递该参数
Intent intent = new Intent(Second.this, AlarmReceiver.class);
intent.putExtra("notificationId", notificationId);
intent.putExtra("time", time);
从HomeActivity中获取传递的参数,并将其设置为TextView,如下所示:
textviewAlarm.setText(time.toSring());