2016-11-14 23 views
0

I所定義有在XML定義的加號線的形狀的筆劃寬度:藉助Android,如何可以在運行時改變在XML

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
<item> 
    <shape android:shape="line" 
     android:id="@+id/line1"> 
     <stroke android:width="15dp" android:color="@android:color/black" /> 
    </shape> 
</item> 
<item> 
    <rotate 
     android:fromDegrees="90" 
     android:pivotX="50%" 
     android:pivotY="50%" 
     android:toDegrees="-90"> 
     <shape android:shape="line" 
      android:id="@+id/line2"> 
      <stroke android:width="15dp" android:color="@android:color/black" /> 
     </shape> 
    </rotate> 
</item> 

在運行時我有時想要改變strokewidth從15dp到其他東西。

我加號添加到一個按鈕,一個id move_button

 <Button 
     android:background="@drawable/plus" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_weight="7" 
     android:id="@+id/move_button" /> 

我能夠以編程方式更改move_button,但我不知道如何設置strokewidth上的線與形狀ID line1line2在運行時。

這是我到目前爲止有:

LayerDrawable layerDrawable = (LayerDrawable)moveButton.getBackground(); //this is not null 
String horLine = "line1"; 
int horLineID = getResources().getIdentifier(horLine, "id", getPackageName()); //this gives an id for the horizontal line 

我不知道下一步該怎麼做來改變筆劃寬度。

任何幫助,將不勝感激。

編輯:

This通過eldivino87回答解決了幾乎等同於我的一個問題,但對於LayerDrawable

+1

我會嘗試設置一個id到圖層中的項目而不是形狀。然後你可以得到像layerDrawable.findDrawableByLayerId()這樣的形狀。您可以將其轉換爲ShapeDrawable,因此您可以訪問Paint對象(getPaint()),並且可以修改它的描邊。 –

+0

@LuisMiguelSierra非常感謝路易斯。其實你的評論加上eldivino87的回答給了我解決方案。轉換爲'ShapeDrawable'給了一個運行時異常,但我會把代碼作爲一個答案,以幫助其他人使用此問題 –

+0

使用漸變drawable而不是layerdrawable。漸變可繪製支持邊框顏色和寬度 –

回答

1

移動ID的列表項,如路易斯提示沒有setStroke方法解決了這個問題:

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:id="@+id/line1"> 
    <shape android:shape="line"> 
     <stroke android:width="15dp" android:color="@android:color/black" /> 
    </shape> 
</item> 
<item android:id="@+id/line2"> 
    <rotate 
     android:fromDegrees="90" 
     android:pivotX="50%" 
     android:pivotY="50%" 
     android:toDegrees="-90"> 
     <shape android:shape="line"> 
      <stroke android:width="15dp" android:color="@android:color/black" /> 
     </shape> 
    </rotate> 
</item> 

然後代碼變爲:

LayerDrawable layerDrawable = (LayerDrawable)moveButton.getBackground(); 
String horLine = "line1"; 
int horLineID = getResources().getIdentifier(horLine, "id", getPackageName()); //this gives an id for the horizontal line 
GradientDrawable hLine = (GradientDrawable) layerDrawable.findDrawableByLayerId(horLineID); 
hLine.setStroke(5, Color.BLACK); 
相關問題