Using PhoneNumberUtils.formatNumber() on API 16

后端 未结 3 1426
孤城傲影
孤城傲影 2021-02-19 12:37

I\'m trying to format numbers to a default country code, and I know how, but when I do it, an error appears saying this is only for API 21. I am targeting API 16. If I use the o

相关标签:
3条回答
  • 2021-02-19 12:40

    This works for me for all version, may be because of backward compatibility support:

    yourTextView.setText(PhoneNumberUtils.formatNumber(yourStringPhone, Locale.getDefault().getCountry()));
    
    0 讨论(0)
  • 2021-02-19 12:48

    Your link to the documentation doesn't identify the format methods you are referring to. I'm guessing the deprecated method is formatNumber(String source).

    While the general definition of "deprecated" includes the possibly of the feature being deleted at some future time, it has been the Android policy to not delete items from the API that will break existing code. An example of this is AbsoluteLayout, which was deprecated in API level 3, and yet remains a part of the API. In Android, "deprecated" is an indication that there is an alternative, better way to achieve the same result, and you are strongly encouraged to use it instead (if possible).

    Here, the improved alternative method is only available in API level 21. To support devices with lower API levels, you can safely used the deprecated method. It's not going away anytime soon.

    Another option is to examine the source code for PhoneNumberUtils to see if you can use pieces of it to create your own formatNumber() method that does what you want and supports API 16 -- probably not worth the effort.

    0 讨论(0)
  • 2021-02-19 12:55

    Following example with deprecated method as mentioned by @qbix.

    A good practice is to check the level of the sdk to use the correct method:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        yourTextView.setText(PhoneNumberUtils.formatNumber(yourStringPhone, Locale.getDefault().getCountry()));
    } else {
        yourTextView.setText(PhoneNumberUtils.formatNumber(yourStringPhone)); //Deprecated method
    }
    
    0 讨论(0)
提交回复
热议问题