FreeRDP
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Modules Pages
IntEditTextPreference.java
1/*
2 EditTextPreference to store/load integer values
3
4 Copyright 2013 Thincast Technologies GmbH, Author: Martin Fleisz
5
6 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
7 If a copy of the MPL was not distributed with this file, You can obtain one at
8 http://mozilla.org/MPL/2.0/.
9*/
10
11package com.freerdp.freerdpcore.utils;
12
13import android.content.Context;
14import android.content.res.TypedArray;
15import android.preference.EditTextPreference;
16import android.util.AttributeSet;
17
18import com.freerdp.freerdpcore.R;
19
20public class IntEditTextPreference extends EditTextPreference
21{
22
23 private int bounds_min, bounds_max, bounds_default;
24
25 public IntEditTextPreference(Context context)
26 {
27 super(context);
28 init(context, null);
29 }
30
31 public IntEditTextPreference(Context context, AttributeSet attrs)
32 {
33 super(context, attrs);
34 init(context, attrs);
35 }
36
37 public IntEditTextPreference(Context context, AttributeSet attrs, int defStyle)
38 {
39 super(context, attrs, defStyle);
40 init(context, attrs);
41 }
42
43 private void init(Context context, AttributeSet attrs)
44 {
45 if (attrs != null)
46 {
47 TypedArray array =
48 context.obtainStyledAttributes(attrs, R.styleable.IntEditTextPreference, 0, 0);
49 bounds_min =
50 array.getInt(R.styleable.IntEditTextPreference_bounds_min, Integer.MIN_VALUE);
51 bounds_max =
52 array.getInt(R.styleable.IntEditTextPreference_bounds_max, Integer.MAX_VALUE);
53 bounds_default = array.getInt(R.styleable.IntEditTextPreference_bounds_default, 0);
54 array.recycle();
55 }
56 else
57 {
58 bounds_min = Integer.MIN_VALUE;
59 bounds_max = Integer.MAX_VALUE;
60 bounds_default = 0;
61 }
62 }
63
64 public void setBounds(int min, int max, int defaultValue)
65 {
66 bounds_min = min;
67 bounds_max = max;
68 bounds_default = defaultValue;
69 }
70
71 @Override protected String getPersistedString(String defaultReturnValue)
72 {
73 int value = getPersistedInt(-1);
74 if (value > bounds_max || value < bounds_min)
75 value = bounds_default;
76 return String.valueOf(value);
77 }
78
79 @Override protected boolean persistString(String value)
80 {
81 return persistInt(Integer.parseInt(value));
82 }
83
84 @Override protected void onDialogClosed(boolean positiveResult)
85 {
86 if (positiveResult)
87 {
88 // prevent exception when an empty value is persisted
89 if (getEditText().getText().length() == 0)
90 getEditText().setText("0");
91
92 // check bounds
93 int value = Integer.parseInt(getEditText().getText().toString());
94 if (value > bounds_max || value < bounds_min)
95 value = bounds_default;
96 getEditText().setText(String.valueOf(value));
97 }
98
99 super.onDialogClosed(positiveResult);
100 }
101}