天天看點

開發中遇到的一些版本相容問題-setBackground

之前在修改某支付sdk的時候需要用到自定義的對話框,其中用到了setBackground這個方法,由于一開始項目的minSdkVersion高,沒有提示,直到到某部手機上運作時出現了下面這個錯誤:

java.lang.NoSuchMethodError: android.view.View.setBackground

才發現,低版本的sdk沒有這個方法,直接使用setBackgroundDrawable代替。

其實setBackground也是調用了setBackgroundDrawable:

/**
     * Set the background to a given Drawable, or remove the background. If the
     * background has padding, this View's padding is set to the background's
     * padding. However, when a background is removed, this View's padding isn't
     * touched. If setting the padding is desired, please use
     * {@link #setPadding(int, int, int, int)}.
     *
     * @param background The Drawable to use as the background, or null to remove the
     *        background
     */
    public void setBackground(Drawable background) {
        //noinspection deprecation
        setBackgroundDrawable(background);
    }
           

如果不想直接使用setBackgroundDrawable,那麼可以加個判斷:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    XXXXXX.setBackground(null);
 } else {   
   XXXXXX.setBackgroundDrawable(null); 
}
           

繼續閱讀