2012-07-30 28 views
4

我試圖使用LayerDrawable作爲自定義UI小部件,並且其中一個圖層的繪製邊界不同於其他圖層,但似乎沒有工作。從本質上講,我的代碼做到這一點:android set bounds for a layer of drawable

int left, top, right, bottom; 
/*... do some math ... */ 
Drawable d = mDrawable.findDrawableByLayerId(R.id.some_specific_layer); 
d.setBounds(left, top, right, bottom); 

同時,XML看起來是這樣的:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" > 

<item> 
    <shape android:shape="rectangle" > 
     <solid android:color="#ff999999" /> 
    </shape> 
</item> 
<item 
    android:id="@id/some_specific_layer" 
    android:drawable="@drawable/some_drawable"/> 

所以最好我會some_drawable看到了一個灰色的矩形,用灰色顯示的金額從後面取決於邊界計算的結果。但我從來沒有看到任何灰色層,而且似乎是因爲它的界限也在某種程度上被設定。

編輯

這裏有一個視覺的期望與預期的結果: enter image description here

頂部圖像是我想達到的目標;灰色對應於第一層並且梯度對應於具有預定義的id的第二層。實際結果從不顯示灰色。

有誰知道是否可以在不影響其他圖層的情況下設置一層LayerDrawable的邊界?

回答

1

我收到了Android Developers Google Group的一些回覆。從本質上講,沒有可靠的方法來與LayerDrawable做到這一點,因爲它管理所有它的子狀態Drawables。自此我採用了一種使用兩個單獨的drawable的方法,並取得了令人滿意的結果。下面是引用話題:

https://groups.google.com/d/topic/android-developers/fUxtJstdkBM/discussion

+0

請添加代碼示例或描述了該問題的解決方案,因爲這個網址和討論的解決方案是不可訪問 – 2017-05-25 11:11:27

+0

不幸的是,我不記得討論的細節,也沒有解決我最終的解決方案。我可能只是使用了背景圖片,或者在畫布上繪製了可繪圖。 – Karakuri 2017-06-12 16:04:58

0

我已經成功地做類似的事情,此代碼,使用LayerDrawable:

// create first shape 
ShapeDrawable shape1 = new ShapeDrawable(new OvalShape()); 
shape1.getPaint().setColor(0xFFFFFF00); 
shape1.setIntrinsicWidth(50); 
shape1.setIntrinsicHeight(50); 
shape1.invalidateSelf(); 

// create second shape 
ShapeDrawable shape2 = new ShapeDrawable(new OvalShape()); 
shape2.getPaint().setColor(0xFFFFB400); 
shape2.setIntrinsicWidth(20); 
shape2.setIntrinsicHeight(50); 
shape2.invalidateSelf(); 

// create layerDrawable (layer-list in xml) 
// it containt our 2 shapes and the order in wich they will be drawn (shape2 is on top). 
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{shape1, shape2}); 

// ajust position shape1 and shape2 
layerDrawable.setLayerInset(0, 0,0,0,0); 
layerDrawable.setLayerInset(1, 15,0,15,0); 

結果是(在黑色背景):

相關問題