Button setTextAppearance is deprecated

▼魔方 西西 提交于 2019-12-30 18:45:32

问题


Button setTextAppearance(Context context, int resid) is deprecated

and setTextAppearance(int resid) - only available for API level 23

What should I use instead?


回答1:


Deprecated means that support will be dropped for it sometimes in the future, but it is still working as expected. On older APIs, there is no alternative, since the new setTextAppearance(int resid) got only released with API level 23.

If you want to be safe for a long time, you can use the following code:

if (Build.VERSION.SDK_INT < 23) {
    yourButton.setTextAppearance(context, resid);
} else {
    yourButton.setTextAppearance(resid);
}

This code prefers the new version on phones with API level 23 or higher, but uses the old one when the API level 23 one isn't available.




回答2:


I am going to say the same this as @Daniel Zolnai. But do not make the check Build.VERSION>SDK_INT < 23 in all the places in your code. Put this in one place, so it will be easy for you to remove this in the future or make changes to it. So how to do it? I will do this for the yourButton case.

  1. Never use Button or any other view provided by android just like that. I say this, because in the future you will need to tweak something and hence it's better to have your own MyButton or something of that sort. So create MyButton extends Button.

  2. Inside MyButton, put the below code:

    public void setTextAppearance(Context context, int resId) {
        if (Build.VERSION.SDK_INT < 23) {
            super.setTextAppearance(context, resId);
        } else {
            super.setTextAppearance(resId);
        }
    }
    


This way you can always use setTextAppearance without needing to worry about checking for BUILD versions. If in future, you plan to remove this whole thing, then you have to refactor in just one place. This is a bit of work, but in the long run, this will help you a lot and will reduce some maintanance nightmares.



来源:https://stackoverflow.com/questions/33393137/button-settextappearance-is-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!