我有一个带有“TimePreference”类的TimePickerDialog首选项,该类扩展了DialogPreference:
public class TimePreference extends DialogPreference{
...
private TimePicker picker=null;
...
public TimePreference(Context ctxt, AttributeSet attrs){
super(ctxt, attrs);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
}
@Override
protected View onCreateDialogView(){
picker=new TimePicker(getContext());
return(picker);
}
...
}
我想添加第三个按钮,它将把首选项设置为当前时间并关闭对话框,如下所示:
问题是,是否可以使用TimePickers进行此操作,还是应该自定义AlertDialog?
最佳答案
感谢您的回答!我将向您展示我最终是如何处理的,以防万一有人想做同样的事情。
首先,我有一个布局文件good_timedialog.xml,它看起来像我想要的:
然后,我有一个TimePreference类:
public class TimePreference extends DialogPreference{
private final static String lTag="CustomTimeDialog";
private TimePicker picker;
protected TimeObj lastTime;
public TimePreference(Context ctxt,AttributeSet atrs) {
super(ctxt,atrs);
setDialogLayoutResource(R.layout.good_timedialog); // this loads the layout
setPositiveButtonText("");
setNegativeButtonText(""); // hide default buttons
setDialogTitle(ctxt.getString(R.string.selectTimeTimePrefTitle));
}
@Override
protected void onBindDialogView(View v){
super.onBindDialogView(v);
v.findViewById(R.id.butCancel).setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Log.d(lTag,"cancel clicked");
getDialog().dismiss();
}
});
v.findViewById(R.id.butNow).setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Log.d(lTag,"now clicked");
saveToSP(true);
getDialog().dismiss();
}
});
v.findViewById(R.id.butOK).setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
Log.d(lTag,"ok clicked");
saveToSP(false);
getDialog().dismiss();
}
});
picker = (TimePicker) v.findViewById(R.id.timePicker);
if (picker!=null) {
picker.setCurrentHour(lastTime.hr);
picker.setCurrentMinute(lastTime.min);
} else { // if it is null
Log.w(lTag,"var picker is null!");
}
}
void saveToSP(boolean now){
if (now) lastTime = new TimeObj(); // make it the current time
else {
lastTime.hr = picker.getCurrentHour();
lastTime.min = picker.getCurrentMinute();
}
setSummary(lastTime.giveString()); // update Summary like hh:mm 16:28
int time = lastTime.giveMinutes(); // 10:30am will be 630 minutes
// save to sharedprefs
if(callChangeListener(time)){
persistInt(time);
if(getEditor().commit()) Log.d(lTag,"Successfully saved changes");
else Log.w(lTag,"Did NOT save changes");
}
}
//... more ...
}
在perferences.xml文件中,我可以使用
<com.example.TimePreference android:key="test"/>