OGeek|极客世界-中国程序员成长平台

标题: android - EditText 自定义字符串格式 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-9 06:50
标题: android - EditText 自定义字符串格式

我搜索了与我的问题类似的每个问题,但没有得到解决。我的问题是这样的:

我想在输入时格式化 EditText 中的字符串。格式如下(始终是 19 位数字):

012345 01 0123456789 0

如您所见,我想在用户输入时添加空格。我知道我必须使用 TextWatcher 但我所做的一切都没有得到我想要的。

编辑:

这是我上次尝试的代码:

        @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);
            }
        }



Best Answer-推荐答案


给你吧。

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());
          }

             }});

    }
}

通过这种方式,我只是设法在特定间隔的数字之间添加空格。

注意:我在edittext中添加了额外的功能,这样就只能输入数字,同时默认只会弹出数字键盘。有关用户输入类型的更多信息,this 可能会对您有所帮助。

关于android - EditText 自定义字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18305520/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) Powered by Discuz! X3.4