【问题标题】:How to resolve setBackgroundDrawable being deprecated如何解决 setBackgroundDrawable 被弃用的问题
【发布时间】:2016-02-07 11:09:06
【问题描述】:

在 Android Studio 上,它一直说 setBackgroundDrawable() 以及 getWidthgetHeight 已弃用。

我该如何解决这个问题?

ivImage.setBackgroundDrawable(gd);
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();

【问题讨论】:

    标签: android android-studio background drawable


    【解决方案1】:

    只需阅读函数的文档,然后按照他们告诉您的去做即可。为了 ImageView.setBackgroundDrawable,文档告诉你使用setBackground

    public void setBackgroundDrawable(可绘制背景) 在 API 级别 1 中添加

    此方法在 API 级别 16 中已弃用。请改用 setBackground(Drawable)

    对于Display 上的getWidthgetHeight,文档告诉您这样做:

    public int getWidth() 在 API 级别 1 中添加

    此方法在 API 级别 13 中已弃用。请改用 getSize(Point)。

    这归结为

    Point point = null;
    getWindowManager().getDefaultDisplay().getSize(point);
    int width = point.x;
    int height = point.y;
    

    【讨论】:

      【解决方案2】:

      只需将.setBackgroundDrawable(gd); 替换为.setBackground(gd);

      这很可能会解决您的问题

      ivImage.setBackground(gd);
      Display display = getWindowManager().getDefaultDisplay();
      int width = display.getWidth();
      int height = display.getHeight();
      

      【讨论】:

        【解决方案3】:

        如果您有资源 ID,那么我们可以使用 setBackgroundResource(),它是 API 级别 1

        int sdk = android.os.Build.VERSION.SDK_INT;
        if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
            setBackgroundDrawable();
        } else {
            setBackground();
        }
        

        根据source,setBackground()只需调用setBackgroundDrawable()

         public void setBackground(Drawable background) {
            setBackgroundDrawable(background);
          }
        
        @Deprecated 
        public void setBackgroundDrawable(Drawable background) { ... }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-10
          • 2019-04-05
          • 2018-01-30
          • 2021-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多