使用 Date/Time 选择器 Android 显示 Date/TIme
Showing Date/TIme with Date/Time Picker Android
我正在尝试设置 Date/Time 用户从 Lollipop Date/Time 选择器中选择。我遇到的问题是 date/time 将设置为按钮文本没问题。问题是它不会保存在它所在的字符串中。然后我想将该字符串用于我知道该怎么做的事情。
日期选择器CLASS
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) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
Date d = new Date(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("EE, MMM dd, yyyy");
// String newDate = sdf.format(d);
Toast.makeText(getActivity(), mMonth, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), mDay, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), mYear, Toast.LENGTH_LONG).show();
}
}
片段CLASS
public class Request extends Fragment {
public TextView mCurrentUser;
public Button Request_Button;
public Button RButton_Date;
public Button RButton_Time;
public String cug;
public String cu;
public String time;
public String date;
//Request newInstance()
public static Request newInstance() {
Request fragment = new Request();
return fragment;
}
//Needed empty Request Constructor
public Request() {
}
//Public onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Make a view
View rootview = inflater.inflate(R.layout.fragment_request, container, false);
//Where you would initialize your variables
RButton_Date =(Button)rootview.findViewById(R.id.Request_Button_Date);
RButton_Time =(Button)rootview.findViewById(R.id.Request_Button_Time);
Request_Button = (Button)rootview.findViewById(R.id.Request_Button_Request);
//Current User Logged In
this.mCurrentUser = (TextView)rootview.findViewById(R.id.Current_User_TV);
date = new SimpleDateFormat("EE, MMM dd, yyyy").format(new Date().getTime());
time = new SimpleDateFormat("h:mm a" ).format(new Date().getTime());
RButton_Time.setText(time);
RButton_Date.setText(date);
//Showing current user
final ParseUser mCurrentUser = ParseUser.getCurrentUser();
if(mCurrentUser == null){
String mCurUserNull = "No User Logged on";
this.mCurrentUser.setText(mCurUserNull);
}
else{
cu = mCurrentUser.get("FirstName").toString();
cug = String.format("Hi! %s do you need a technician today?", cu);
this.mCurrentUser.setText(cug);
}
//=================================================================
//Create Dialog
RButton_Date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Do Stuff
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
});
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
};
RButton_Time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment picker1 = new TimePickerFragment();
picker1.show(getFragmentManager(), "timePicker");
}
});
Request_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Write Code for Gathering Variables and sending request email!!!
//Gather user info
//Populate email
//Send Username Request to Request@BitsNBytesStore.com
Toast.makeText(getActivity(), cu + " Requested a tech at "+time
+", on "+date, Toast.LENGTH_SHORT).show();
}
});
//return rootview
return rootview;
}
我不明白我做错了什么。它产生资源未知的错误。我用谷歌搜索,广泛搜索 Whosebug。 2014 年及更早的所有内容都不起作用。
目标
我只想让用户选择 date/time 用作可以设置为按钮内文本的字符串。我正在使用 Google 中的示例代码
.
编辑
ONDATESET
public void onDateSet(DatePicker view, int year, int month, int day) {
Button DateButton = (Button) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.Request_Button_Date);
String stringDueDateFrag = (month+1) + "/" + day + "/" + year + " ";
DateButton.setText(stringDueDateFrag);
// Set up a Calendar object to capture the user selected date in case the user wants
// edit the date later. Put the user selected date in a Bundle for onCreateDialog function to use.
}
ONTIMESET
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Button TimeButton = (Button) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.Request_Button_Date);
String stringDueDateFrag = hourOfDay + ":" + minute;
TimeButton.setText(stringDueDateFrag);
}
日志
11-08 15:07:39.229 4922-4966/com.megliosolutions.bitsnbytes W/EGL_emulation: eglSurfaceAttrib not implemented
11-08 15:07:39.229 4922-4966/com.megliosolutions.bitsnbytes W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5486920, error=EGL_SUCCESS
11-08 15:07:59.658 4922-4929/com.megliosolutions.bitsnbytes W/art: Suspending all threads took: 15.332ms
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: FATAL EXCEPTION: main
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: Process: com.megliosolutions.bitsnbytes, PID: 4922
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.DatePickerDialog.resolveDialogTheme(DatePickerDialog.java:88)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.DatePickerDialog.<init>(DatePickerDialog.java:105)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.DatePickerDialog.<init>(DatePickerDialog.java:82)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at com.megliosolutions.bitsnbytes.Adapters.DatePickerFragment.onCreateDialog(DatePickerFragment.java:40)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:308)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:458)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5257)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
11-08 15:08:06.175 4922-4929/com.megliosolutions.bitsnbytes W/art: Suspending all threads took: 5.023ms
尝试将 targetFragment
设置为 Request
并在 Request
片段中实现回调。这样您就可以访问调用片段本身中的 Date/Time。
在您的 DatePickerFragment 中,删除 OnDateSetListener 并检索从 Request
传递的 Target 片段。
上有非常好的资源
public class DatePickerFragment extends DialogFragment {
private DatePickerDialog.OnDateSetListener dateSetListener;
public DatePickerFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
dateSetListener = (DatePickerDialog.OnDateSetListener) getTargetFragment();
} catch (Exception e) {
Log.i("~!@#$", e.getMessage());
}
}
@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(), dateSetListener, year, month, day);
}
}
现在在您的 Request
片段中,调用 setTargetFragment。
public class Request extends Fragment implements OnDateSetListener {
...
public Request() {
// Required empty public constructor
}
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
...
RButton_Date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.setTargetFragment(MyFragmentDemo.this, 12345);
picker.show(getFragmentManager(), "datePicker");
}
});
...
return rootView;
}
// Override the onDateSet() callback here.
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// get the Date and do as you require.
}
}
可行的解决方案
我已经想出如何让它完美地工作。
您需要确保为两个 Time/Datepickers 创建一个单独的 class。但是,不要使用 "implements OnDateSetListener" 而只是保留 class 的原样或删除它,并在要使用它的 activity/fragment 中实现 OnDateSetListener。
您可以通过这种方式将两者结合起来:
implements OnDateSetListener, OnTimeSetListener...
这将允许同时使用两者,但您必须实施所需的方法。那你就可以开始了。
确保正确初始化所有内容,并将所有内容放置在需要以编程方式进行的位置。
你可以试试这个对我有用
public class DatePickerFragment extends DialogFragment {
private static final String ARG_DATE = "date";
public static final String EXTRA_DATE =
"com.bignerdranch.android.criminalintent.date";
private DatePicker mDatePicker;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Date date = (Date)getArguments().getSerializable(ARG_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date,null);
mDatePicker = (DatePicker)view.findViewById(R.id.dialog_date_date_picker);
mDatePicker.init(year,month,day,null);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int year = mDatePicker.getYear();
int month = mDatePicker.getMonth();
int day = mDatePicker.getDayOfMonth();
Date date = new GregorianCalendar(year, month, day).getTime();
sendResult(Activity.RESULT_OK, date);
}
})
.create();
}
public static DatePickerFragment newInstance(Date date){
Bundle args = new Bundle();
args.putSerializable(ARG_DATE,date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode,Date date){
if (getTargetFragment() == null){
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_DATE,date);
getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,intent);
}
}
并在片段中调用
mDateButton = (Button) view.findViewById(R.id.crime_date);
updateDate((mCrime.getDate()).toString());
/*mDateButton.setEnabled(false);*/
/* Design a date picker for an application */
mDateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
/*DatePickerFragment dialog = new DatePickerFragment();*/
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fragmentManager, DIALOG_DATE);
}
});
我正在尝试设置 Date/Time 用户从 Lollipop Date/Time 选择器中选择。我遇到的问题是 date/time 将设置为按钮文本没问题。问题是它不会保存在它所在的字符串中。然后我想将该字符串用于我知道该怎么做的事情。
日期选择器CLASS
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) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
Date d = new Date(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("EE, MMM dd, yyyy");
// String newDate = sdf.format(d);
Toast.makeText(getActivity(), mMonth, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), mDay, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), mYear, Toast.LENGTH_LONG).show();
}
}
片段CLASS
public class Request extends Fragment {
public TextView mCurrentUser;
public Button Request_Button;
public Button RButton_Date;
public Button RButton_Time;
public String cug;
public String cu;
public String time;
public String date;
//Request newInstance()
public static Request newInstance() {
Request fragment = new Request();
return fragment;
}
//Needed empty Request Constructor
public Request() {
}
//Public onCreateView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Make a view
View rootview = inflater.inflate(R.layout.fragment_request, container, false);
//Where you would initialize your variables
RButton_Date =(Button)rootview.findViewById(R.id.Request_Button_Date);
RButton_Time =(Button)rootview.findViewById(R.id.Request_Button_Time);
Request_Button = (Button)rootview.findViewById(R.id.Request_Button_Request);
//Current User Logged In
this.mCurrentUser = (TextView)rootview.findViewById(R.id.Current_User_TV);
date = new SimpleDateFormat("EE, MMM dd, yyyy").format(new Date().getTime());
time = new SimpleDateFormat("h:mm a" ).format(new Date().getTime());
RButton_Time.setText(time);
RButton_Date.setText(date);
//Showing current user
final ParseUser mCurrentUser = ParseUser.getCurrentUser();
if(mCurrentUser == null){
String mCurUserNull = "No User Logged on";
this.mCurrentUser.setText(mCurUserNull);
}
else{
cu = mCurrentUser.get("FirstName").toString();
cug = String.format("Hi! %s do you need a technician today?", cu);
this.mCurrentUser.setText(cug);
}
//=================================================================
//Create Dialog
RButton_Date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Do Stuff
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
});
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
};
RButton_Time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment picker1 = new TimePickerFragment();
picker1.show(getFragmentManager(), "timePicker");
}
});
Request_Button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Write Code for Gathering Variables and sending request email!!!
//Gather user info
//Populate email
//Send Username Request to Request@BitsNBytesStore.com
Toast.makeText(getActivity(), cu + " Requested a tech at "+time
+", on "+date, Toast.LENGTH_SHORT).show();
}
});
//return rootview
return rootview;
}
我不明白我做错了什么。它产生资源未知的错误。我用谷歌搜索,广泛搜索 Whosebug。 2014 年及更早的所有内容都不起作用。
目标
我只想让用户选择 date/time 用作可以设置为按钮内文本的字符串。我正在使用 Google 中的示例代码 .
编辑
ONDATESET
public void onDateSet(DatePicker view, int year, int month, int day) {
Button DateButton = (Button) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.Request_Button_Date);
String stringDueDateFrag = (month+1) + "/" + day + "/" + year + " ";
DateButton.setText(stringDueDateFrag);
// Set up a Calendar object to capture the user selected date in case the user wants
// edit the date later. Put the user selected date in a Bundle for onCreateDialog function to use.
}
ONTIMESET
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Button TimeButton = (Button) getActivity().getWindow().getDecorView().getRootView().findViewById(R.id.Request_Button_Date);
String stringDueDateFrag = hourOfDay + ":" + minute;
TimeButton.setText(stringDueDateFrag);
}
日志
11-08 15:07:39.229 4922-4966/com.megliosolutions.bitsnbytes W/EGL_emulation: eglSurfaceAttrib not implemented
11-08 15:07:39.229 4922-4966/com.megliosolutions.bitsnbytes W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa5486920, error=EGL_SUCCESS
11-08 15:07:59.658 4922-4929/com.megliosolutions.bitsnbytes W/art: Suspending all threads took: 15.332ms
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: FATAL EXCEPTION: main
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: Process: com.megliosolutions.bitsnbytes, PID: 4922
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.DatePickerDialog.resolveDialogTheme(DatePickerDialog.java:88)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.DatePickerDialog.<init>(DatePickerDialog.java:105)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.DatePickerDialog.<init>(DatePickerDialog.java:82)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at com.megliosolutions.bitsnbytes.Adapters.DatePickerFragment.onCreateDialog(DatePickerFragment.java:40)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.DialogFragment.getLayoutInflater(DialogFragment.java:308)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:458)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5257)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
11-08 15:08:04.618 4922-4922/com.megliosolutions.bitsnbytes E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
11-08 15:08:06.175 4922-4929/com.megliosolutions.bitsnbytes W/art: Suspending all threads took: 5.023ms
尝试将 targetFragment
设置为 Request
并在 Request
片段中实现回调。这样您就可以访问调用片段本身中的 Date/Time。
在您的 DatePickerFragment 中,删除 OnDateSetListener 并检索从 Request
传递的 Target 片段。
public class DatePickerFragment extends DialogFragment {
private DatePickerDialog.OnDateSetListener dateSetListener;
public DatePickerFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
dateSetListener = (DatePickerDialog.OnDateSetListener) getTargetFragment();
} catch (Exception e) {
Log.i("~!@#$", e.getMessage());
}
}
@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(), dateSetListener, year, month, day);
}
}
现在在您的 Request
片段中,调用 setTargetFragment。
public class Request extends Fragment implements OnDateSetListener {
...
public Request() {
// Required empty public constructor
}
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
...
RButton_Date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.setTargetFragment(MyFragmentDemo.this, 12345);
picker.show(getFragmentManager(), "datePicker");
}
});
...
return rootView;
}
// Override the onDateSet() callback here.
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// get the Date and do as you require.
}
}
可行的解决方案
我已经想出如何让它完美地工作。
您需要确保为两个 Time/Datepickers 创建一个单独的 class。但是,不要使用 "implements OnDateSetListener" 而只是保留 class 的原样或删除它,并在要使用它的 activity/fragment 中实现 OnDateSetListener。
您可以通过这种方式将两者结合起来:
implements OnDateSetListener, OnTimeSetListener...
这将允许同时使用两者,但您必须实施所需的方法。那你就可以开始了。
确保正确初始化所有内容,并将所有内容放置在需要以编程方式进行的位置。
你可以试试这个对我有用
public class DatePickerFragment extends DialogFragment {
private static final String ARG_DATE = "date";
public static final String EXTRA_DATE =
"com.bignerdranch.android.criminalintent.date";
private DatePicker mDatePicker;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Date date = (Date)getArguments().getSerializable(ARG_DATE);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date,null);
mDatePicker = (DatePicker)view.findViewById(R.id.dialog_date_date_picker);
mDatePicker.init(year,month,day,null);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int year = mDatePicker.getYear();
int month = mDatePicker.getMonth();
int day = mDatePicker.getDayOfMonth();
Date date = new GregorianCalendar(year, month, day).getTime();
sendResult(Activity.RESULT_OK, date);
}
})
.create();
}
public static DatePickerFragment newInstance(Date date){
Bundle args = new Bundle();
args.putSerializable(ARG_DATE,date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode,Date date){
if (getTargetFragment() == null){
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_DATE,date);
getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,intent);
}
}
并在片段中调用
mDateButton = (Button) view.findViewById(R.id.crime_date);
updateDate((mCrime.getDate()).toString());
/*mDateButton.setEnabled(false);*/
/* Design a date picker for an application */
mDateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
/*DatePickerFragment dialog = new DatePickerFragment();*/
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fragmentManager, DIALOG_DATE);
}
});