首页 文章

如何从资源创建Drawable

提问于
浏览
254

我有一个图像 res/drawable/test.png (R.drawable.test) .
我想将此图像传递给接受 Drawable 的函数 .
(例如mButton.setCompoundDrawables())

那么如何将图像资源转换为 Drawable

6 回答

  • 13

    您的Activity应该具有getResources方法 . 做:

    Drawable myIcon = getResources().getDrawable( R.drawable.icon );
    
  • 22

    此代码已弃用 .

    Drawable drawable = getResources().getDrawable( R.drawable.icon );

    使用此instad .

    Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);
    
  • 1

    自API 22起, getDrawable (int id) 方法已折旧 .

    相反,您应该使用 getDrawable (int id, Resources.Theme theme) for API 21

    代码看起来像这样 .

    Drawable myDrawable;
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
        myDrawable = context.getResources().getDrawable(id, context.getTheme());
    } else {
        myDrawable = context.getResources().getDrawable(id);
    }
    
  • 2

    我想补充一点,如果在使用getDrawable(...)时收到“已弃用”消息,则应使用支持库中的以下方法 .

    ContextCompat.getDrawable(getContext(),R.drawable.[name])
    

    使用此方法时,您不必使用getResources() .

    这相当于做类似的事情

    Drawable mDrawable;
    if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
        mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]);
    } else {
        mDrawable = getResources().getDrawable(R.id.[name]);
    }
    

    这适用于Lollipop前后版本 .

  • 113

    Get Drawable from vector resource irrespective of, whether its vector or not:

    AppCompatResources.getDrawable(context, R.drawable.icon);
    

    Note:
    ContextCompat.getDrawable(context, R.drawable.icon); 将为矢量资源生成 android.content.res.Resources$NotFoundException .

  • 525

    如果您尝试从图像设置为的视图中获取drawable,

    ivshowing.setBackgroundResource(R.drawable.one);
    

    那么drawable将仅使用以下代码返回null值...

    Drawable drawable = (Drawable) ivshowing.getDrawable();
    

    因此,如果您想从特定视图中检索drawable,最好使用以下代码设置图像 .

    ivshowing.setImageResource(R.drawable.one);
    

    只有这样,我们才能准确地改造抽屉 .

相关问题