如何在设置android:background后以编程方式更改按钮颜色以使其成为圆角?

时间:2016-01-15 06:54:09

标签: android-layout

我的布局中有6个按钮。所有这些都使用自定义xml使用单个xml文件在android:background中使其圆角。但是现在,如何以编程方式更改每个按钮的颜色?由于已使用android:background

1 个答案:

答案 0 :(得分:0)

这是代码。

1.在mybutton.xml中的可绘制文件夹中创建一个xml文件并粘贴以下标记:

function async_post($host,$path,$data){

    $post = http_build_query($data);
    $len = strlen($post);
    $fp = fsockopen( $host , 80, $errno, $errstr, 30);
    if (!$fp) {
        echo "$errstr ($errno)\n";
    } else {

        $out = "POST $path HTTP/1.1\r\n";
        $out .= "Host: $host\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Content-Length: $len\r\n";
        $out .= "\r\n";
        $out .= $post."\r\n";
        fwrite($fp, $out);
        fclose($fp);
    }
}

2.现在使用此drawable作为视图的背景。如果视图是按钮,那么类似这样:

<?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="#5e7974" />
         <gradient android:angle="-90" android:startColor="#345953" android:endColor="#689a92"  />            
     </shape>
 </item>
<item android:state_focused="true">
     <shape android:shape="rectangle"  >
         <corners android:radius="3dip" />
         <stroke android:width="1dip" android:color="#5e7974" />
         <solid android:color="#58857e"/>       
     </shape>
 </item>  
<item >
    <shape android:shape="rectangle"  >
         <corners android:radius="3dip" />
         <stroke android:width="1dip" android:color="#5e7974" />
         <gradient android:angle="-90" android:startColor="#8dbab3" android:endColor="#58857e" />            
     </shape>
 </item>
</selector>

用于换色使用方式