具有背景色选择器的按钮-单击时,背景色扩展到按钮之外 [英] Button with selector for background color - when clicked the background color is extending out of the button
问题描述
首先,.按钮是通过代码动态添加的,因此无法在xml中应用样式.
To begin with.. the button is added dynamically through code and hence cannot apply the styles in xml.
我的活动中没有几个按钮,并且我正在使用选择器来更改背景颜色.该按钮还带有一个形状",用于边框.
I have few buttons in my activity and i am using a selector to change the background color. The button also has a "shape" attached to it, for border.
image_border.xml
image_border.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/dark_grey" />
<stroke
android:width="4dp"
android:color="@color/light_grey" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
button_background_blue.xml
button_background_blue.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/blue" android:state_pressed="true"/>
<item android:drawable="@color/dark_grey" android:state_focused="true"/>
<item android:drawable="@drawable/image_border"/>
</selector>
现在,当我单击按钮时,背景颜色会改变得很好.但是,背景色超出了按钮的大小.我不确定它在哪里发生.
Now when i click on the button, the background color, changes just fine. But, the background color is extending beyond the button's size. I am not sure where it is happening.
请参考下面的图片...
Please refer to the images below...
点击按钮之前:
点击按钮后:
我认为颜色正在延伸到填充物之类的东西中,但是我真的不太确定为什么会这样.
I think the color is extending into the padding or something, but i am really not pretty sure, why this is occuring.
推荐答案
这应该是您的选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/image_border_blue" android:state_pressed="true"/>
<item android:drawable="@drawable/image_border_dark_grey" android:state_focused="true"/>
<item android:drawable="@drawable/image_border"/>
</selector>
并添加以下可绘制对象:
And just add these drawables:
image_border_blue
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/blue" />
<stroke
android:width="4dp"
android:color="@color/light_grey" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
image_border_dark_grey
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/dark_grey" />
<stroke
android:width="4dp"
android:color="@color/light_grey" />
<padding
android:bottom="4dp"
android:left="4dp"
android:right="4dp"
android:top="4dp" />
</shape>
这篇关于具有背景色选择器的按钮-单击时,背景色扩展到按钮之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!