Android button, xml文件定义形状,代码中修改背景颜色

1. 首先在drawable文件夹定义一个shape.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#e6e6" />

    <corners
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp" />

    <padding
        android:left="30dp"
        android:top="0dp"
        android:right="30dp"
        android:bottom="0dp"
        />
</shape>


2. 在main.xml文件中,button使用这个shape.xml,如下:

<Button
        android:id="@+id/button_next"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="@string/button_next"
        android:textSize="@dimen/label_text_size"
        android:layout_alignParentBottom="true"
        android:layout_centerVertical="true"
        android:gravity="center_horizontal|center_vertical"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:background="@drawable/shape"
        />

这时,该button就显示如shape.xml定义的形状。


3. 在代码中动态修改button 背景颜色,代码如下:

GradientDrawable bgShape = (GradientDrawable)buttonNext.getBackground();
bgShape.setColor(Color.BLUE);


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。