可绘制资源的ID

时间:2013-05-05 13:31:14

标签: android

如何从android:drawableLeft动态更改drawable的位置到android:drawableRight / left / bottom? 我知道,我应该使用setCompoundDrawablesWithIntrinsicBounds方法,但首先我需要知道R.drawable。 * 并在setCompoundDrawablesWithIntrinsicBounds方法中使用它。

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);
    }    
}

所以,我需要view的可绘制资源的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); 
}

1 个答案:

答案 0 :(得分: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];
}