最近两天学到了几个xml使用的小技巧,记录在这里备忘,也希望能帮到路过的大家。
其实下面的效果,如果有美工配合,都不是问题,但是,往往身边没有美工小伙伴,或者“美工女王”的气场比较强大,不想轻易麻烦人家,那么下面的小技巧就会变得比较实用。另外,祝程序猿都能找到美工妹子做老婆,男女搭配,干活不累,^_^~
自动选择背景图/背景颜色
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@android:color/darker_gray"></item>
<item android:state_pressed="false" android:drawable="@android:color/white"></item>
</selector>
其中,可选的状态类型包括:
android:state_pressed=["true" | "false"] android:state_focused=["true" | "false"] android:state_selected=["true" | "false"] android:state_checkable=["true" | "false"] android:state_checked=["true" | "false"] android:state_enabled=["true" | "false"] android:state_window_focused=["true" | "false"]没有过多好解释的,selector是最常用的东东
自定义形状
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape=["rectangle" | "oval" | "line" | "ring"] >
<corners
android:radius="integer"
android:topLeftRadius="integer"
android:topRightRadius="integer"
android:bottomLeftRadius="integer"
android:bottomRightRadius="integer" />
<gradient
android:angle="integer"
android:centerX="integer"
android:centerY="integer"
android:centerColor="integer"
android:endColor="color"
android:gradientRadius="integer"
android:startColor="color"
android:type=["linear" | "radial" | "sweep"]
android:useLevel=["true" | "false"] />
<padding
android:left="integer"
android:top="integer"
android:right="integer"
android:bottom="integer" />
<size
android:width="integer"
android:height="integer" />
<solid
android:color="color" />
<stroke
android:width="integer"
android:color="color"
android:dashWidth="integer"
android:dashGap="integer" />
</shape>
shape支持多种效果,最常用的的是做圆角:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="5dp"></corners>
<solid android:color="#FF0000"></solid>
</shape>
还有做边框:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke android:width="2dp" android:color="@android:color/black"></stroke>
<solid android:color="@android:color/white"></solid>
</shape>
strock中的dashwith和dashGap属性还可以实现虚线的效果。
此外,shape还可以实现渐变色(<gradient>标签),椭圆(android:shape="ovel"),环形(android:shape="ring")等效果。
平铺背景图
默认情况下,背景图不够大时,Android会拉伸背景图,而可能我们需要的是一个平铺效果。本来,我原本想通过.9png图来解决的,但是,.9png图实际上是一个可选择的拉伸,貌似无法实现平铺效果,所以,下面的手法可能会好使一些:
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/ic_launcher" android:tileMode="repeat">
</bitmap>