android 解决setbackgrounddrawable过时
今天,簡單講講android如何解決 
setbackgrounddrawable過時的問題。
 
之前,自己也講了一些函數的過時的替代函數,昨天,自己在代碼里又發現了setbackgrounddrawable過時,于是自己在網上查找了資料,最終解決了問題。這里記錄一下。
 
setBackgroundDrawable()在API 16(4.1)已經過時了
 
 
4.1之后有兩種方法可以代替:
a、使用setBackgroundResource替代
 
setBackgroundDrawable
換為
setBackgroundResource
即可。
且傳入的參數直接是resource的id,無需再去通過ID獲得View,更加方便。
附上對應的API的解釋:
| void android.view.View.setBackgroundResource(int resid) public void setBackgroundResource (int resid)Added inAPI level 1 Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background. Related XML Attributes
 Parametersresid? | 
 
 
b、使用setBackground替代
 
 
例如:
textView.setBackgroundResource(R.drawable.icon); textView.setBackground(ContextCompat.getDrawable(this, R.drawable.icon));
 
setBackgroundResource方法在內部還是調用的setBackground方法,而setBackground內部調用的還是setBackgroundDrawable方法
setBackground源碼:
public void setBackground(Drawable background) {//noinspection deprecationsetBackgroundDrawable(background);//這里}
 
setBackgroundResource源碼:
@RemotableViewMethodpublic void setBackgroundResource(@DrawableRes int resid) {if (resid != 0 && resid == mBackgroundResource) {return;}Drawable d = null;if (resid != 0) {d = mContext.getDrawable(resid);}setBackground(d);//注意這里的調用mBackgroundResource = resid;}
 
 
這里簡單講講,雖然setBackground和setBackgroundResource都可以替代setbackgrounddrawable,但是setBackground是從API 16以后才有的,之前沒有這個函數。所以最好使用setBackgroundResource,這個方法是從Api 1開始就有,所以就不用擔心了。
 
如有需要使用setBackground,需要判斷API的版本,其實也很簡單:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {setBackground(drawable); } else {setBackgroundDrawable(drawable); }對于API大于或等于16 的 android 版本,使用setBackground,對于API小于16的版本,使用setBackgroundDrawable。
 
android 解決setbackgrounddrawable過時就講完了。
 
就這么簡單。
總結
以上是生活随笔為你收集整理的android 解决setbackgrounddrawable过时的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: android addView的使用
- 下一篇: android Drawable.mut
