So I've created a custom preference using DialogPreference - nothing terribly special; invoked via XML, runs without any major errors:
public class TimePref extends DialogPreference {
private TimePicker picker;
private int value;
private final static int DEFAULT_VALUE = 0;
public TimePref(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TimePref(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected View onCreateDialogView() {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
picker = new TimePicker(getContext());
picker.setLayoutParams(layoutParams);
FrameLayout dialogView = new FrameLayout(getContext());
dialogView.addView(picker);
return dialogView;
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
picker.setIs24HourView(true);
setTimePicker(getValue());
}
@Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
picker.clearFocus();
int newValue;
if (Build.VERSION.SDK_INT >= 23 ) {
newValue = picker.getHour() * 60;
newValue += picker.getMinute();
} else {
newValue = picker.getCurrentHour() * 60;
newValue += picker.getCurrentMinute();
}
if (callChangeListener(newValue)) {
setValue(newValue);
}
}
}
@Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getInt(index, DEFAULT_VALUE);
}
@Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
if (restorePersistedValue) {
if (defaultValue != null)
setValue((int) defaultValue);
} else {
setValue(getPersistedInt(DEFAULT_VALUE));
}
}
public void setValue(int value) {
this.value = value;
persistInt(this.value);
}
public int getValue() {
return this.value;
}
private void setTimePicker (int value) {
if (Build.VERSION.SDK_INT >= 23 ) {
picker.setHour((int) (value / 60));
picker.setMinute(value % 60);
} else {
picker.setCurrentHour((int) (value / 60));
picker.setCurrentMinute(value % 60);
}
}
}
Problem arises when I want to access it programmatically, for example:
TimePref p = (TimePref) findPreference(prefKey);
p.setValue(value);
Will return p as null and this throw a java.lang.NullPointerException. So the question is how can one access a custom preference programmatically if you cannot 'find' it?