- 首页 > it技术 > >
仿照DatePickerFragment实现的TimePickerFragment
public class TimePickerFragment extends DialogFragment {
public staticfinal String EXTRA_HOUR="com.example.purplefragment.extra_hour";
public static final String EXTRA_MINUTE="com.example.purplefragment.extra_minute";
private static final String CURRENT_TIME_HOUR="com.example.purplefragment.current_time_hour";
private static final String CURRENT_TIME_MINUTE="com.example.purplefragment.current_time_minute";
private TimePicker mTimePicker;
public static TimePickerFragment newInstance(int hour,int minute)
{
Bundle bundle=new Bundle();
bundle.putInt(CURRENT_TIME_HOUR,hour);
bundle.putInt(CURRENT_TIME_MINUTE,minute);
TimePickerFragment dialog=new TimePickerFragment();
dialog.setArguments(bundle);
return dialog;
}@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
int hour=getArguments().getInt(CURRENT_TIME_HOUR);
int minute=getArguments().getInt(CURRENT_TIME_MINUTE);
View v= LayoutInflater.from(getActivity())
.inflate(R.layout.dialog_time,null);
mTimePicker=(TimePicker)v.findViewById(R.id.time_picker);
mTimePicker.setCurrentHour(hour);
mTimePicker.setCurrentMinute(minute);
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.time_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
int hour=mTimePicker.getCurrentHour();
int minute=mTimePicker.getCurrentMinute();
sendResult(Activity.RESULT_OK,hour,minute);
}
})
.create();
}private void sendResult(int resultCode,int hour,int minute)
{
if(getTargetFragment()==null)
return;
Intent intent=new Intent();
intent.putExtra(EXTRA_HOUR,hour);
intent.putExtra(EXTRA_MINUTE,minute);
getTargetFragment().onActivityResult(getTargetRequestCode(),resultCode,intent);
}
}
mTimeButton=(Button)v.findViewById(R.id.crime_time);
Calendar calendar=Calendar.getInstance();
calendar.setTime(mCrime.getDate());
//一开始没有加final时
//使用newInstance方法传参数时会提示
// hour be accessed from within inner class,shoule be declare final
final int hour=calendar.get(Calendar.HOUR_OF_DAY);
final int minute=calendar.get(Calendar.MINUTE);
mTimeButton.setText(hour+":"+minute);
mTimeButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v)
{
mIsChange=true;
FragmentManager fragmentManager=getFragmentManager();
TimePickerFragment dialog=TimePickerFragment.newInstance(hour,minute);
dialog.setTargetFragment(CrimeFragment.this,REQUEST_TIME);
dialog.show(fragmentManager,DIALOG_TIME);
setIsChangeResult();
}
});
//为什么之前个体extra默认值设为0的时候,我只点了修改日期的按钮
//时间会被重置为0呢,讲道理没有执行这个方法啊
if(requestCode==REQUEST_TIME){
int hour=intent.getIntExtra(TimePickerFragment.EXTRA_HOUR,mCrime.getDate().getHours());
int minute=intent.getIntExtra(TimePickerFragment.EXTRA_MINUTE,mCrime.getDate().getMinutes());
mTimeButton.setText(hour+":"+minute);
mCrime.getDate().setHours(hour);
mCrime.getDate().setMinutes(minute);
updateDate();
}
推荐阅读