How to create Drawable from resource

前端 未结 8 1569
臣服心动
臣服心动 2020-12-04 07:48

I have an image res/drawable/test.png (R.drawable.test).
I want to pass this image to a function which accepts Drawable, e.g. mButton.set

相关标签:
8条回答
  • 2020-12-04 08:22

    The getDrawable (int id) method is deprecated as of API 22.

    Instead you should use the getDrawable (int id, Resources.Theme theme) for API 21+

    Code would look something like this.

    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);
    }
    
    0 讨论(0)
  • 2020-12-04 08:25

    I would just like to add that if you are getting "deprecated" message when using getDrawable(...) you should use the following method from the support library instead.

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

    You do not have to use getResources() when using this method.

    This is equivalent to doing something like

    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]);
    }
    

    This works on both pre and post Lollipop versions.

    0 讨论(0)
  • 2020-12-04 08:26

    If you are inheriting from a fragment you can do:

    Drawable drawable = getActivity().getDrawable(R.drawable.icon)

    0 讨论(0)
  • 2020-12-04 08:31

    Your Activity should have the method getResources. Do:

    Drawable myIcon = getResources().getDrawable( R.drawable.icon );
    
    0 讨论(0)
  • 2020-12-04 08:33

    If you are trying to get the drawable from the view where the image is set as,

    ivshowing.setBackgroundResource(R.drawable.one);
    

    then the drawable will return only null value with the following code...

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

    So, it's better to set the image with the following code, if you wanna retrieve the drawable from a particular view.

     ivshowing.setImageResource(R.drawable.one);
    

    only then the drawable will we converted exactly.

    0 讨论(0)
  • 2020-12-04 08:36

    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); will produce android.content.res.Resources$NotFoundException for vector resource.

    0 讨论(0)
提交回复
热议问题