android-drawable/mipmap&Drawable实例的多种创建方式&Theme和Style的区别。

本文详细介绍了Android中资源文件的加载方法,包括不同API级别下的使用方式,并对比了使用Drawable的不同方法,同时给出了BitmapDrawable和ColorDrawable的具体创建实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

res路径下drawable和mipmap在Java代码里的使用是一样的。

过时用法:

context.getResources().getDrawable(R.mipmap.header));
context.getResources().getDrawable(R.drawable.header);

在V4包里这样用

Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.header);



总结:

将资源文件转化为drawable使用

Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.header);




Added in API level 21 还可以直接
Drawable drawable = context.getDrawable(R.mipmap.header);


在 APIlevel21 以后可以给drawable添加主题。不好用不推荐。

Drawable getDrawable (int id,  Resources.Theme theme) 

Return a drawable object associated with a particular resource ID and styled for the specified theme. Various types of objects will be returned depending on the underlying resource -- for example, a solid color, PNG image, scalable image, etc.

 
  
  
 
  

如何使用带Theme的方法呢?

getResources().getDrawable(R.mipmap.header, getTheme())







++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

drawable的多种创建方式

看看其子类




我们最常用的是: BitmapDrawable和ColorDrawable


代码示例

colorDrawable支持的类型

  Supported formats are:
 #RRGGBB
 #AARRGGBB
 or one of the following names:
 red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta',
 yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey',
 aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 
'silver', 'teal'.

new ColorDrawable(Color.parseColor("yellow"));
new ColorDrawable(Color.parseColor("#00000000"));

 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.header);
 BitmapDrawable drawable = new BitmapDrawable(bitmap);




Theme和style的区别

Theme 和 Style的作用一样,都通过设置不同的值(图片、大小、布尔值)给控件,让一个控件或多个控件自定义风格。但Theme是针对窗体级别的,改变窗体样式;而Style是针对窗体元素级别的,改变指定控件或者Layout的样式。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值