setBackground、setBackgroundDrawable、setBackgroundResource、setBackgroundColor的區別

在 Android 開發中,咱們經常遇到對 View 組件的背景顏色或者背景圖片進行一些動態的設置。那麼常見的這四種方法每每分不清楚,下面咱們來看下它們之間的不一樣之處。java

    1. setBackground(Drawable background) 方法的參數是一個Drawable對象.該方法用於設置view組件的背景圖片。其中 Drawable 對象能夠這樣獲取:
Drawable background = getResources().getDrawable(R.drawable.xxx); 
複製代碼
    1. setBackgroundDrawable(Drawable background) 方法跟setBackground大致相同。
    1. setBackgroundResource(int resId) 方法的參數是一個組件的id值。該方法也是用於加載組件的背景圖片的。
    1. setBackgroundColor(Color.XXX) 方法參數爲一個 Color 類的靜態常量,它是用來設置背景顏色的方法。

咱們在動態設置背景顏色或圖片時,有可能該背景顏色有圓角,若是咱們直接設置背景顏色,那麼原先的圓角就會沒有了。因此,若是背景顏色有圓角的話,就不能直接設置了。咱們使用以下的方法解決。git

Drawable drawable = tv.getBackground();
if (null != drawable && drawable instanceof GradientDrawable) {
    // 這種狀況是設置了帶shape的背景顏色
    ((GradientDrawable)drawable).setColor(Color.GREEN);
}
複製代碼





About Megithub

相關文章
相關標籤/搜索