0

如何动态地将可绘制的位置从 android:drawableLeft 更改为 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);
    }    
}

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

1 回答 1

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];
}
于 2013-05-05T13:39:03.337 回答