2017-05-16 81 views
3

我有這個xml在哪裏我已經設置了筆觸顏色,但我有時我想要以編程方式更改stoke顏色。文件名是dummy.xmlJava android xml文件中改變顏色

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

    <stroke 
     android:width="1dp" 
     android:color="#ff000000" /> 

    <padding 
     android:bottom="1dp" 
     android:left="1dp" 
     android:right="1dp" 
     android:top="1dp" /> 

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

我想改變顏色(筆觸顏色)編程,我可怎麼辦呢?

我用這個XML這裏:

<LinearLayout 
       android:layout_marginTop="2dp" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:id="@+id/a" 
       android:layout_gravity="center" 
       android:background="@drawable/dummy" 
       android:layout_marginBottom="2sp" 
       android:orientation="horizontal" 
       android:padding="5dp"> 

       <RelativeLayout 
        android:id="@+id/serverStatusWrapper" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginLeft="2dp" 
        android:background="@drawable/shadow_green" 
        android:padding="2dp"> 

        <ImageView 
         android:id="@+id/serverStatus" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_centerInParent="true" 
         android:antialias="true" 
         android:src="@drawable/ic_settings_input_antenna_white_24dp" /> 

       </RelativeLayout> 

       <RelativeLayout 
        android:id="@+id/locationStatusWrapper" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:background="@drawable/shadow_red" 
        android:padding="2dp"> 

        <ImageView 
         android:id="@+id/locationStatus" 
         android:layout_width="wrap_content" 
         android:layout_height="wrap_content" 
         android:layout_centerInParent="true" 
         android:antialias="true" 
         android:src="@drawable/ic_warning_white_24dp" /> 
       </RelativeLayout> 

      </LinearLayout> 
+0

您需要動態地創建繪製我有嘗試這一點,但不是爲我工作 –

回答

3
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.a); 

可以更改行程作爲

GradientDrawable drawable = (GradientDrawable)linearLayout.getBackground(); 
drawable.setStroke(3, Color.RED); 

而且可以改變固體顏色

GradientDrawable drawable = (GradientDrawable)linearLayout.getBackground(); 
drawable.setColor(Color.RED); 

希望這有助於

+0

好吧,但這個XML我的LinearLayout –

+0

使用然後改變ImageView的到的LinearLayout –

+0

我嘗試這樣做,但我有空指針:GradientDrawable drawable =(GradientDrawable)linearLayout.getBackground(); –