問題描述
我搜索了與我的問題類似的每個問題,但沒有得到解決.我的問題是這樣的:
I searched every question similar to my problem but didn't get it working. My problem is this:
我想在輸入時格式化 EditText
中的字符串.格式如下(始終是 19 位數字):
I want to format a string in EditText
while typing. The format is this (it's always a 19 digit number):
012345 01 0123456789 0
如您所見,我想在用戶輸入時添加空格.我知道我必須使用 TextWatcher
但我所做的一切都沒有得到我想要的.
As you can see I want to add spaces when they are needed while the user is typing. I know that I have to use the TextWatcher
but everything I do I don't get what i want.
編輯:
這是我上次嘗試的代碼:
Here is the code of my last try:
@Override
public void afterTextChanged(Editable s) {
if(s.length() == 7 || s.length() == 10 || s.length() == 21){
editText.removeTextChangedListener(this);
String newValue;
newValue= s.insert((s.length()-1), " ").toString();
//Log.d("AFTER",newValue);
editText.setText(newValue);
editText.setSelection(newValue.length());
editText.addTextChangedListener(this);
}
}
推薦答案
給你.
ma??in.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:digits="0123456789"
android:inputType="number" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity {
int textlength = 0;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after)
{
}
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
String text = editText.getText().toString();
textlength = editText.getText().length();
if(text.endsWith(" "))
return;
if(textlength == 7 || textlength == 10 || textlength == 21)
{
editText.setText(new StringBuilder(text).insert(text.length()-1, " ").toString());
editText.setSelection(editText.getText().length());
}
}});
}
}
通過這種方式,我只是設法在特定間隔的數字之間添加空格.
In this way, I have just managed to add spaces between the digits at particular intervals.
注意:我在edittext中添加了額外的功能,這樣就只能輸入數字,同時默認只會彈出數字鍵盤.有關用戶輸入類型的更多信息,this 可能會對你有所幫助.
Note: I have added extra features to the edittext, so that only numbers can be entered and at the same time the number keyboard only pops up by default. For more on the way for the type of user inputs, this might help you.
這篇關于EditText 自定義字符串格式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!