EditText custom string formatting

后端 未结 1 396
梦如初夏
梦如初夏 2021-01-18 22:24

I searched every question similar to my problem but didn\'t get it working. My problem is this:

I want to format a string in EditText while typing. The

相关标签:
1条回答
  • 2021-01-18 22:45

    Here you go with it.

    main.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.

    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.

    0 讨论(0)
提交回复
热议问题