在公司做一个样式布局 用到了描述背景的drawable/中的 xml文件,本来是一个很简单的问题,先上效果图
其实就是通过切换按钮改变按钮效果,圆角效果就不讨论了,现在只是想讨论一下中间那个按钮出现的问题,
设计思路:
当中间那个按钮失去焦点的时候,通过setBackgroundResource方法将xml资源设置进去,其实就是两边加两条竖线
xml文件代码
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/unselected"
android:bottom="-2dp"
android:top="-2dp"
>
<shape>
<stroke
android:width="1dp"
android:color="#fff"
/>
</shape>
</item>
</layer-list>
结果出现如下效果
,发现在原来的布局文件中的padding参数消失了,这里可能有人会问,为什么要用layer-list进行包裹,解释一下,由于
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/unselected"
android:bottom="-2dp"
android:top="-2dp"
>
<shape>
<stroke
android:width="1dp"
android:color="#fff"
/>
<padding android:left="6dp" android:top="6dp" android:right="6dp" android:bottom="6dp" />
</shape>
</item>
</layer-list>
效果恢复正常
第二种改法:
<shape>
<stroke
android:width="1dp"
android:color="#fff"
/>
</shape>
直接用shape,有人会问,这样不是会出现四条描边吗,确实会出现四条,但是上下两条会和父容器的外边框重合,记住是重合,不是像linearlayout那样顺序摆放,所以上下两个边框有没有也就无所谓了。此处如果shape加了而不做认为padding参数赋值,则会出现原有padding被清零的结果,也就是本文所讨论的padding失效问题。
第三种方法:
先拿到前一布局的padding,然后修改背景,再通过setPadding方法设置
int left = textView.getPaddingLeft();
int top = textView.getPaddingTop();
int right = textView.getPaddingRight();
int bottom = textView.getPaddingBottom();
textView.setBackgroundResource(R.drawable.xx);
textView.setPadding(left, top, right, bottom);