Android开发学习之路--Drawable mutations
来源:互联网 发布:凯程网络课程 编辑:程序博客网 时间:2024/06/03 07:07
时间过得很快,明天终于可以拿到房子了,交完这次房租,也可以成为房东了,看看博客也好久没有更新了,最近一直在整机器人,也没有太多时间整理博客。
今天下午和同事一起遇到了一个问题,就是明明没有改变一个控件的alpha值,但是这个控件的透明度居然变了。甚是奇怪之余,大神在stackoverflow上去提了问题,最后也有另外的大神给了正确的回复。
最终我们知道了是android的Drawable mutations的一些小细节问题,具体的可以参考一篇讲解Drawable mutations很好的文章。
其实是android为了节省内存,把资源给共享了,如果两个控件的drawable使用了相同的资源,可能是相同的图片资源,可能是相同的颜色,或者其他。
可能还是不是非常理解,那我们就来个例子吧,首先我们新建个activity的layout文件,如下:
<Button android:id="@+id/test1" android:layout_width="80dp" android:layout_height="100dp" android:background="@android:color/holo_green_dark" android:text="tes1"/> <Button android:id="@+id/test2" android:layout_width="100dp" android:layout_height="80dp" android:layout_marginTop="10dp" android:background="@android:color/holo_green_dark" android:text="test2" /> <SeekBar android:id="@+id/seekBar_1" android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:max="255"/>
这里省略了,只显示需要的控件,其中test1和test2的background是一样的,然后seeker是之后为了改变透明度使用。那就开始写测试的代码吧:
Button test1 = (Button)findViewById(R.id.test1); Button test2 = (Button)findViewById(R.id.test2); SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar_1); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { test1.getBackground().setAlpha(255-progress); test2.invalidate(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { }
这里通过拖动seekbar,然后改变button1的alpha值,这里没有设置button2的alpha,只是button2刷新了下。可以看下效果:
显然我们没有设置button2的background,那为什么button2的背景透明度也变换了呢?其实就是如上所说的资源共享了,两个button,我们都用了同一个的颜色,所以系统把公用了同一个颜色的资源,那么当我们改变button1的颜色的时候,button2的alpha值也会跟着改变。
但是很多时候我们确实需要只改变一个控件的状态而不是改变两个,那要怎么处理呢?这就是这里要讲的mutations了,mutation意为变化,突变的意思,这里如果使用mutation的话,那么就会只改变一个颜色了,那么我们修改i下代码:
test1.getBackground().mutate().setAlpha(255-progress);
修改设置alpha的方法,使用mutate()方法,然后运行看下效果:
如上图,我们得到了很好的实践。
- Android开发学习之路--Drawable mutations
- Drawable Mutations(Android Drawable 深入分析)
- Drawable Mutations(Android Drawable 深入分析)
- Drawable Mutations(Android Drawable 深入分析)
- Drawable Mutations(Android Drawable 深入分析)
- Drawable Mutations
- Android学习之路------layer-list drawable
- Android 开发之 Drawable系列
- Android学习之路------自定义drawable之shape属性
- FreeCodeCamp学习--Mutations
- vuex学习五----Mutations
- Drawable Mutations--绘图变异
- android开发文档之resource-drawable用法
- Android样式的开发之drawable
- Android开发素材之drawable妙用
- android开发 之常用的drawable(一)
- Android开发之drawable中的命名问题
- Android Graphics.drawable之—ShapeDrawable学习
- 6P的宽度375VS414
- 用Python递归实现汉诺塔问题
- 16.7.7 T1:YL杯超级篮球赛
- 修改tableview索引条背景颜色变透明或其他颜色的方法
- 卷二 MFC中简单控件使用
- Android开发学习之路--Drawable mutations
- (OK) 图解几个与Linux网络虚拟化相关的虚拟网卡-VETH/MACVLAN/MACVTAP/IPVLAN
- java基础学习总结——面向对象2
- 优先队列的应用
- chattr命令详解
- 90%汽车业创新来自电子业,九大IC原厂畅谈产业趋势
- PHP原生态分页
- 51NOD 1267 4个数和为0(二分 + 排序)
- 2016.7.7 一次低级错误导致的产品缺陷