2013-05-05 193 views
0

如何動態地將drawable的位置從android:drawableLeft更改爲android:drawableRight/left/bottom? 我知道,我應該使用setCompoundDrawablesWithIntrinsicBounds方法,但首先我需要知道R.drawable。 *並在setCompoundDrawablesWithIntrinsicBounds方法中使用它。可繪製資源的ID

private void changeLabelPosition(View view){ 
    int drawableID = 
    if(getGravity = Gravity.LEFT){ 
     view.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, 0, 0); 
    }else if(getGravity = Gravity.TOP){ 
     view.setCompoundDrawablesWithIntrinsicBounds(0, drawableID, 0 , 0); 
    }else if(getGravity = Gravity.RIGHT){ 
     view.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawableID, 0); 
    }else if(getGravity = Gravity.BOTTOM){ 
     view.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, drawableID); 
    }  
} 

所以,我需要視圖的可繪製資源的ID。

這種方式是不恰當的,原因有很多按鈕,而它`不是好辦法,使用硬編碼:

drawableID = 0; 
switch (view.getId()){ 
case R.id.button_add: 
    drawableID = R.drawable.button_add; 
case R.id.button_remove: 
    drawableID = R.drawable.button_remove; 
... 
... 
... 
} 
if(getGravity = Gravity.LEFT){ 
    view.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0, 0, 0); 
} 
... 
... 
... 
enter code here 

編輯

switch (mMainPanelGravity) 
{ 
case Gravity.TOP: 
for (View v : arrayOfViews) 
{ 
Drawable[] drawables = ((TextView) v) .getCompoundDrawables(); 
if (drawables.length != 0) { 
Drawable dr = drawables[0]; 
((TextView) v).setCompoundDrawablesWithIntrinsicBounds(null, dr, null, null); 
} 

回答

0

setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom)還將接受Drawable

你得到Drawable的視圖,你可以直接設置它

Drawable drawable=yourview.getBackground(); 

然後

view.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null) 

編輯:

Drawable[] drawables = view.getCompoundDrawables() 

if(drawables.length!=0) 
{ 
Drawable drawable=drawable[0]; 
} 
+0

無法正常工作。背景是透明的 – ant 2013-05-05 14:33:53

+0

@ user2038145不行,在這個意義上,首先明確你試圖實現的是什麼 – Pragnani 2013-05-06 00:44:44

+0

drawable的位置是從xml文件設置爲android:drawableRight。 – ant 2013-05-06 09:44:37