一、Shape的使用
1.gradient 渐变
startColor和endColor不用说;
angle表示方向角度。当angle=0时,渐变色是从左向右。 然后逆时针方向转,当angle=90时为从下往上;
android:type="linear" linear代表线性渐变;sweep代表角度渐变,以中心点为射线的一个断点,顺时针旋转所扫过的区域;radial代表镜像渐变,从中心向外,如果是圆形的话,需要在shape里面添加android:shape="oval"
<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" > <gradient android:endColor="#0000FF" android:gradientRadius="100%p" android:startColor="#FF0000" android:type="radial" /></shape>
2.corners 圆角
android:radius为角的弧度,值越大角越圆。还可以设置四个角的弧度:
<corners
android:topRightRadius="20dp" 右上角
android:bottomLeftRadius="20dp" 右下角
android:topLeftRadius="1dp" 左上角
android:bottomRightRadius="0dp" 左下角
/>
这里有个地方需要注意,bottomLeftRadius是右下角,而不是左下角,不过不影响使用。
3.padding 内边距,不多说
4.size 设置width和height
5.color 设置颜色
6.solid 填充色,需要注意的是有些图片是半透明的,此时要设置一下solid,以免图片的背景为默认的背景色,如黑色
7.stroke 描边
可设置color和width,可以将 dashWidth和dashGap组合使用,模拟虚线,dashWidth为虚线长,dashGap为虚线间隔
8.普通属性就不加讨论了
<padding android:left=""/>
<size android:width=""/>
<solid android:color=""/>
<stroke android:dashWidth=""/>
=========================================================================
再简单记录下点击效果,不仅适用于button,也适用于imageview,textview。
首先在drawable中定义正常效果button_bg
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!--
<corners
android:bottomRightRadius="5dp"
android:topRightRadius="5dp" />
-->
<corners android:radius="5dp" />
<solid android:color="#e63232" />
<stroke
android:width="0.5dp"
android:color="#f25561" />
</shape>
然后定义按下之后的效果button_bg_press
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<!--
<corners
android:bottomRightRadius="5dp"
android:topRightRadius="5dp" />
-->
<corners android:radius="5dp" />
<solid android:color="#c93842" />
<stroke
android:width="0.5dp"
android:color="#f25561" />
</shape>
接下来定义selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="false" android:drawable="@drawable/button_bg"></item>
<item android:state_pressed="true" android:drawable="@drawable/button_bg_press"></item>
</selector>
给控件设置背景为
@drawable/selector即可
当然selector中还有很多的属性,如focus,windowfocus等,以后再补充
=====================================================================
再添加一个小技巧
在弹出dialog或者popwindow的时候,我们经常会自定义布局,有的布局是圆角的,通过shape可以很容易实现,但是有时候会发现弹出的窗口是圆角,但是四个角上还有黑色的棱角,解决方法如下:
getWindow().setBackgroundDrawable(new BitmapDrawable());
或者getWindow().setBackgroundDrawableResource(android.R.color.transparent);
=========================================
在代码中设置drawable方向
Drawable d = getResources().getDrawable(R.drawable.home_search_img);
d.setBounds(0, 0, d.getMinimumWidth(), d.getMinimumHeight());
edtkeyword.setCompoundDrawables(d, null, null, null);