[英]How to change button background colour without changing onclick/onpress colors
[英]Change android button colour on click without changing border colour?
我是Android新手,正在设置xml文件。 有没有一种方法可以在单击按钮时以一种“单击”的感觉来更改按钮的颜色,然后又返回到其原始颜色,而无需更改边框的颜色? 我正在使用日食。 谢谢
首先,您需要在Drawable文件夹中制作一些xml文件:
btn_clicked.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="20dp" />
<solid android:color="#ff0000" />
<stroke
android:width="1dp"
android:color="#fff" />
</shape>
btn_normal.xml:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="20dp" />
<solid android:color="#00ff00" />
<stroke
android:width="1dp"
android:color="#fff" />
</shape>
name_btn.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_clicked" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_normal"/>
</selector>
然后像这样使用它:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button android:layout_width="140dp" android:layout_height="40dp"
android:background="@drawable/cancel_btn" />
</RelativeLayout>
AndroidGeek,
您可以在可绘制文件夹下的.XML文件中指定效果,然后将文件链接到布局文件夹下的Button。
例:
在您的activity_main.xml内部,您的Button标记将如下所示:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Styled Button"
android:id="@+id/styledButton"
android:background="@drawable/button"/>
在res / drawable文件夹下创建一个XML文件[示例:button.xml],以指定按下按钮时将发生的更改。
以下是button.xml的内容
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Changes that the button has to show when it is pressed -->
<item android:state_pressed="true" >
<shape>
<solid
android:color="#ef4444" />
<!-- Keep the stroke values same if you want the same border effect, irrespective you press / un-press the button
In case ih you want to change the border thickness, while the button is being clicked,
then increase the "android:width" value -->
<stroke
android:width="1dp"
android:color="#992f2f" />
<corners
android:radius="6dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
<!-- Default appearance when the button is displayed -->
<item>
<shape>
<gradient
android:startColor="#ef4444"
android:endColor="#992f2f"
android:angle="270" />
<stroke
android:width="1dp"
android:color="#992f2f" />
<corners
android:radius="6dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
希望这可以帮助。 不管IDE如何,它都应该起作用。 Eclipse和Android Studio。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.