I have a PreferenceScreen
where 3 of its preferences are TimePreferences
. TimePreference
is a custom class extending DialogPreference
, and it contains a TimePicker
. I created it following THIS CODE.
Now I want to limit the TimePicker
input. Each TimePreference
needs to have a specific time limit (this limit will be different in each TimePreference
), and I'm going to use this limit to check the input values. I.e., I may want the first TimePreference
to be inferior to 1 hour, the 2nd to 5 hours and the last one without limits.
Since I wanted to avoid having 3 different classes I was looking for a way to send some data to the preference. I tried to use defaultValue, but it's null when the user has already selected any value.
My PreferenceActivity uses a PreferenceFragment
. This is their code:
public class PrefsActivity extends Activity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new PrefsFragment()).commit();
}
}
public class PrefsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs_tod);
}
}
Can I send this data to the preference? Or should I have 3 different classes?
Thanks!
You can create custom preference with additional attributes, in your case with limit
attribute.
res/values/attrs.xml
<declare-styleable name="CustomPreference">
<attr name="limit" format="integer"/>
</declare-styleable>
CustomPreference.java
public class CustomPreference extends DialogPreference {
private int limit;
public CustomPreference(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomPreference, 0, 0);
limit = a.getInteger(R.styleable.CustomPreference_limit, 0);
a.recycle();
}
In preference layout:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.example.package">
<PreferenceCategory>
<com.example.package.CustomPreference
android:key="@string/pref_key"
android:title="@string/pref_title"
app:limit="6" />
</PreferenceCategory>
</PreferenceScreen>
Also you can set an attribute value programmatically