简体   繁体   中英

How to get into a variable only a part of the entered in EditText?

How to get into a variable in Java only part of the text or numbers entered in EditText (android). For example, from the entered number 123456789 to get only the first three digits 123?

Looked on the Inte.net but didnt find anything sensible

You can use the substring method to get the number of characters you want:

String num = editText.toString().substring(0,3); //<-- gets the first 3 
                                                    characters of input

https://www.javatpoint.com/java-string-substring

You can use this:

    EditText editText = findViewById(R.id.edit_text);
    if (editText.getText().toString().length() >= 2){
       String slice = editText.getText().toString().substring(0,2);
    } else {
        slice = editText.getText().toString();
    }
    Log.d("TAG", "slice = " + slice);

With this code, you can get first three digit or if editText has less numbers, you get max digits.

Examples: https://www.programiz.com/java-programming/library/string/substring

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM