圆角背景方向相反问题
项目开发中有时需要为Button等控件设置圆角的背景。设置圆角背景的方法为在drawable中新建一个如下形式的xml文件,然后将该Drawable设置到View的android:background属性上即可。xml中topLeftRadius,topRightRadius,bottomRightRadius,bottomLeftRadius分别表示左上角,右上角,右下角和左下角的圆角。
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#AAAAAA" />
<corners android:topLeftRadius="5dp"
android:topRightRadius="5dp"
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"/>
</shape>
显示效果如图所示。
上述xml为四个角都配置了圆角,有时我们希望只有一部分角为圆角。
例如下面这个界面,需要“取消”按钮只有左下角为圆角,而“确定”按钮只有右下角为圆角。
实现一个圆角也很简单,就在xml中只配置一个圆角就可以了。例如
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#AAAAAA" />
<corners android:bottomLeftRadius="5dp"/>
</shape>
这里就只配置了左下角的圆角,上述配置正常显示的效果应该是这样的。
但实际测试发现在某些情况下显示的效果却是这样的。也就是设置的左下角圆角显示的却是右下角的圆角。
这个问题在只设置bottomRightRadius,也就是左下角时也会出现,但是在左上角和右上角不会出现。
问题原因及解决方法
此问题是Android3.0及其以下版本中的一个bug [2]。
解决方法是在res中新建一个drawable-v12的文件夹,在drawable-v12的文件夹中放置正确圆角方法的配置文件,而在drawable文件夹中放置相反圆角方向的配置文件。
上述例子中在drawable-v12文件夹中xml文件配置为
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#AAAAAA" />
<corners android:bottomLeftRadius="5dp"/>
</shape>
在drawable文件夹中xml文件配置为
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#AAAAAA" />
<corners android:bottomRightRadius="5dp"/>
</shape>
Android在获取该Drawable对象时,如果系统版本android 3.0以上就会读取drawable-v12文件夹中的xml文件,如果是android 3.0及其以下版本就会读取drawable文件夹中的xml文件,而drawable文件夹中的xml文件配置的圆角方向正好是相反的,然后系统又显示反了,这样也就变相的让其显示正确了。
参考:
1. http://stackoverflow.com/questions/3056232/how-to-make-a-shape-with-left-top-round-rounded-corner-and-left-bottom-rounded-co
2. http://code.google.com/p/android/issues/detail?id=9161