Set a drawable as background programmatically

佐手、 提交于 2019-12-03 06:21:53
peter

Try this

iv.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.img));

or

iv.setBackgroundResource(R.drawable.img);

Now as getDrawable and setBackgroundDrawable both are depricated you should set drawable as Background like this :

view.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable)); 

and if you are targating minSdk below 16 then make a check like this :

if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {
        view.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.your_drawable));
    } else {
        view.setBackground(ContextCompat.getDrawable(this, R.drawable.your_drawable));
    }

Here the new Method

recyclerView.setBackgroundResource(R.drawable.edit_text_button_shape);

don't use this it's an old method recyclerView.setBackgroundDrawable(this.getResources().getDrawable(edit_text_button_shape));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!