android中,设置imageview的setBackground后怎么不让整体布局重绘
时间: 2024-02-24 11:53:56 浏览: 23
在设置`ImageView`的背景后,如果不想让整体布局重绘,可以调用`ImageView`的`invalidate()`方法,它只会重绘`ImageView`本身,而不会重绘整个布局。
示例代码如下:
```java
imageView.setBackground(backgroundDrawable);
imageView.invalidate();
```
此外,如果你想让`ImageView`的背景在不同状态下有不同的显示效果,可以考虑使用`StateListDrawable`。`StateListDrawable`是一种可以根据不同状态显示不同背景的Drawable,可以在`ImageView`的`setBackground()`方法中使用。这样,当`ImageView`的状态发生变化时,它的背景也会相应地变化,不需要手动调用`invalidate()`方法。
示例代码如下:
```java
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, pressedDrawable);
stateListDrawable.addState(new int[] {android.R.attr.state_focused}, focusedDrawable);
stateListDrawable.addState(new int[] {}, normalDrawable);
imageView.setBackground(stateListDrawable);
```