我想在首选项屏幕中设置一个时间选择器,允许用户选择开始时间和结束时间,并将其像其他设置一样存储为持久值。
您能否展示设置它所需的所有编码,因为我无法通过搜索找到类似的东西。
我在想也许时间选择器应该在对话框中,但我还不知道如何设置它们。如果您可以展示调用带有开始和结束时间时间选择器的对话框的代码,以及如何保存该信息以供以后从首选项屏幕检索,那就太好了。
我们将不胜感激所有的帮助。
真的, 埃马德
最佳答案
我有一个简单的 TimePreference
我在我的一本书中使用的:
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;
public class TimePreference extends DialogPreference {
private int lastHour=0;
private int lastMinute=0;
private TimePicker picker=null;
public static int getHour(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[0]));
}
public static int getMinute(String time) {
String[] pieces=time.split(":");
return(Integer.parseInt(pieces[1]));
}
public TimePreference(Context ctxt, AttributeSet attrs) {
super(ctxt, attrs);
setPositiveButtonText("Set");
setNegativeButtonText("Cancel");
}
@Override
protected View onCreateDialogView() {
picker=new TimePicker(getContext());
return(picker);
}
@Override
protected void onBindDialogView(View v) {
super.onBindDialogView(v);
picker.setCurrentHour(lastHour);
picker.setCurrentMinute(lastMinute);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
lastHour=picker.getCurrentHour();
lastMinute=picker.getCurrentMinute();
String time=String.valueOf(lastHour)+":"+String.valueOf(lastMinute);
if (callChangeListener(time)) {
persistString(time);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return(a.getString(index));
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
String time=null;
if (restoreValue) {
if (defaultValue==null) {
time=getPersistedString("00:00");
}
else {
time=getPersistedString(defaultValue.toString());
}
}
else {
time=defaultValue.toString();
}
lastHour=getHour(time);
lastMinute=getMinute(time);
}
}
此的生产级实现将为两个按钮标题使用字符串资源。它还可能对值进行更多错误检查,以防某些代码通过 SharedPreferences.Editor
更新它并且没有正确格式化它。
关于android - 您如何根据首选项创建开始时间和结束时间时间选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7484108/