我希望EditTextPreference只接受6000到65536之間的值,我該怎麼辦?謝謝!如何創建僅接受預定義範圍值的EditTextPreference?
BTW,代碼中的不工作,我不能輸入任意數量的EditTextPreference的編輯框,其關鍵是 「WebServerPort」
<EditTextPreference
android:key="WebServerPort"
android:defaultValue="6000"
android:title="Port"
android:summary="Set port for web server, it should be greater than 6000 and less than 65536"
android:inputType="number"
android:layout="@layout/layout_customize_preference_item"
/>
代碼A
public class UIPreference extends PreferenceActivity {
private AdView adView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.mypreference);
setContentView(R.layout.layout_preference);
EditTextPreference edit_Pref = (EditTextPreference) getPreferenceScreen().findPreference("WebServerPort");
edit_Pref.getEditText().setFilters(new InputFilter[]{ new InputFilterMinMax("6000", "65536")});
}
}
class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
請參閱此鏈接「http://stackoverflow.com/questions/14212518/is-there-a-way-到限定-A-最小和-MAX值換的EditText功能於機器人」。它會幫助你。 – Harshitha