我想在我的应用中使用datepicker。我按照http://developer.android.com/guide/topics/ui/controls/pickers.html中的步骤开发了应用程序。
它有一个在选择日期时调用的方法。
public void onDateSet(DatePicker view, int year, int month, int day) {
Toast.makeText(getContext(),"The date is: " + year + month + day ,Toast.LENGTH_LONG).show();
// Do something with the date chosen by the user
}
现在我想在主要活动中使用日期。上述方法属于不同类:
package com.example.shiza.cube26;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;
import android.widget.Toast;
import java.util.Calendar;
/**
* Created by Shiza on 04/10/2015.
*/
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
Toast.makeText(getContext(),"The date is: " + year + month + day ,Toast.LENGTH_LONG).show();
// Do something with the date chosen by the user
}
}
我想将值表单onDateSet获取到MainActivity。我怎样才能做到这一点?请帮我解决这个问题。
编辑1:
我正在使用sharedprefrence来解决上述问题:
protected void onResume() {
super.onResume();
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
Toast.makeText(this,"I am in on resume",Toast.LENGTH_LONG).show();
SharedPreferences sharedPreferences = this.getSharedPreferences("DATE_OF_JOURNEY", Context.MODE_PRIVATE);
date = sharedPreferences.getString("DATE_OF_JOURNEY",null);
if ( date == null )
{
sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month + "/" + year).apply();
}
date_text.setText(date);
}
我写这样的日期:
public void onDateSet(DatePicker view, int year, int month, int day) {
sharedPreferences = getActivity().getSharedPreferences("DATE_OF_JOURNEY", Context.MODE_PRIVATE);
Toast.makeText(getContext(),"The date is: " + year + month + day ,Toast.LENGTH_LONG).show();
sharedPreferences.edit().putString("DATE_OF_JOURNEY", day + "/" + month+"/"+ year).apply();
// Do something with the date chosen by the user
}
但是,仍然高于代码不起作用?
答案 0 :(得分:0)
一种选择是使用SharedPreferences
并在那里保存您的年,月和日。然后阅读MainActivity的onResume()
回调中的值。
另一种选择是在DatePickerFragment中创建一个接口,并在MainActivity中实现此接口。
修改强>:
您也可以创建自定义BroadcastReceiver,然后在onDateSet()
中发送邮件并在MainActivity