2013-05-05 104 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