gpt4 book ai didi

android - 如何创建仅接受预定义范围值的 EditTextPreference?

转载 作者:行者123 更新时间:2023-11-30 00:35:45 25 4
gpt4 key购买 nike

我希望 EditTextPreference 只接受 6000 到 65536 之间的值,我该怎么做?谢谢!

顺便说一句,代码 A 不起作用,我无法在 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;
}
}

最佳答案

您可以为您的 EditText 分配一个 TextWatcher 并在那里监听文本更改,例如:

editTextPreference.getEditText().addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {

}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {

}

@Override
public void afterTextChanged(Editable s) {
try {
long val = Long.parseLong(s.toString());
if(val > 65536) {
s.replace(0, s.length(), "65536", 0, 5);
} else if(val < 6000) {
s.replace(0, s.length(), "6000", 0, 4);
}
} catch (NumberFormatException ex) {
// Do something
}
}
});

关于android - 如何创建仅接受预定义范围值的 EditTextPreference?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com