我有几个按钮。我想在按下按钮时更改其颜色。并将其他按钮的颜色更改为正常状态。
问题在于,简单地更改按钮的背景后,它的形状也会改变。更改颜色后,带有阴影的默认android按钮将仅替换为具有更高按钮高度的绘制矩形。是的。可以将正常位置和按下位置的按钮定义为可绘制的XML。但是我想使用默认的android按钮而不是花哨的我的按钮。
我的代码如下:
buttonAny.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonAny.setBackgroundColor(COLOR_BUTTON_SELECTED);
buttonMale.setBackgroundColor(COLOR_BUTTON_GRAY);
buttonFemale.setBackgroundColor(COLOR_BUTTON_GRAY);
}
});
buttonMale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonAny.setBackgroundColor(COLOR_BUTTON_GRAY);
buttonMale.setBackgroundColor(COLOR_BUTTON_SELECTED);
buttonFemale.setBackgroundColor(COLOR_BUTTON_GRAY);
}
});
XML:
<Button
android:id="@+id/buttonGenderAny"
android:layout_marginLeft="@dimen/dim1"
android:layout_marginRight="@dimen/dim1"
android:gravity="center"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:text='Any'
android:textColor="@color/text1"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="@+id/buttonGenderMale"
android:layout_marginLeft="@dimen/dim1"
android:layout_marginRight="@dimen/dim1"
android:gravity="center"
android:layout_centerHorizontal="true"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:text='Male'
android:textColor="@color/text1"
android:textAppearance="?android:attr/textAppearanceSmall" />
启动后我的应用程序如下图pic1(对不起,我无权发布图像)
我按下按钮后,如下所示:pic2
非常奇怪的是,按钮的大小已更改。
谷歌有很多类似的问题。但似乎他们不适合我。例如这个链接。但是还没有写出如何在drawable中定义普通按钮或按下按钮。
所以。更改(切换)一些按钮的颜色的最佳方法是什么。谢谢!
在您的可绘制资源下使用要应用于按钮的属性创建一个新的xml文件...例如...
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#c53e2b" />
<gradient android:angle="-90" android:startColor="#a11005" android:endColor="#d62608" />
</shape>
</item>
<item android:state_focused="true">
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#c53e2b" />
<solid android:color="#e0341e"/>
</shape>
</item>
<item >
<shape android:shape="rectangle" >
<corners android:radius="3dip" />
<stroke android:width="1dip" android:color="#c53e2b" />
<gradient android:angle="-90" android:startColor="#ff6c52" android:endColor="#e0341e" />
</shape>
</item>
</selector>
然后在点击监听器中像这样...
buttonMale.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
buttonAny.setBackgroundResource(R.drawable.YOUR_XML_NAME);
buttonMale.setBackgroundResource(R.drawable.YOUR_XML_NAME);
buttonFemale.setBackgroundResource(R.drawable.YOUR_XML_NAME);
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句