问题描述
我有一个EditTextPreference定义为:
I have a EditTextPreference defined as:
<EditTextPreference
android:defaultValue="8888"
android:key="someKey"
android:title="SomeString"
android:inputType="number"
>
EditTextPreference内部使用一个EditText,可以通过EditTextPreference.getEditText()
获得.
EditTextPreference uses an EditText internally which can be obtained with EditTextPreference.getEditText()
.
我想将用户可以输入的数字限制在1024到65535之间的整数范围内.我该怎么做?
I would like to limit the number the user can input to a range of integers between 1024 and 65535. How can I do that?
我尝试同时使用InputFilter和TextWatcher,但没有成功.
I tried to use both an InputFilter and a TextWatcher without success.
有什么想法吗?
您可能已经猜到我正在尝试验证输入的网络端口.也许我应该为此使用其他输入方式?
As you might have guessed I am trying to validate inputting a network port. Maybe I should use some other kind of input for this?
推荐答案
您可以使用EditText进行此操作,但是使用 NumberPicker .
You can do this using a EditText, but it would be much easier using a NumberPicker.
它具有针对您需要的预定义方法: setMinValue( int), setMaxValue(int).
It has predefined methods for what you want: setMinValue(int), setMaxValue(int).
寻求灵感:
import android.content.Context;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.NumberPicker;
/*
* Add this to your XML resource.
*/
public class NumberPickerPreference extends DialogPreference {
private NumberPicker numberPicker;
public NumberPickerPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected View onCreateDialogView() {
return generateNumberPicker();
}
public NumberPicker generateNumberPicker() {
numberPicker = new NumberPicker(getContext());
numberPicker.setMinValue(1025);
numberPicker.setMaxValue(65535);
numberPicker.setValue(1025);
/*
* Anything else you want to add to this.
*/
return numberPicker;
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
int port = numberPicker.getValue();
Log.d("NumberPickerPreference", "NumberPickerValue : " + port);
}
}
}
这篇关于如何将EditTextPreference限制为范围1024:65535的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!