Android中View绘制各种状态的背景图片原理深入分析以及StateListDrawable使用

/* Call this to force a view to update its drawable state. This will cause

  • drawableStateChanged to be called on this view. Views that are interested

  • in the new state should call getDrawableState.

*/

//主要功能是根据当前的状态值去更换对应的背景Drawable对象

public void refreshDrawableState() {

mPrivateFlags |= DRAWABLE_STATE_DIRTY;

//所有功能在这个函数里去完成

drawableStateChanged();

}

/* This function is called whenever the state of the view changes in such

  • a way that it impacts the state of drawables being shown.

*/

// 获得当前的状态属性— 整型集合 ; 调用Drawable类的setState方法去获取资源。

protected void drawableStateChanged() {

//该视图对应的Drawable对象,通常对应于StateListDrawable类对象

Drawable d = mBGDrawable;

if (d != null && d.isStateful()) { //通常都是成立的

//getDrawableState()方法主要功能:会根据当前View的状态属性值,将其转换为一个整型集合

//setState()方法主要功能:根据当前的获取到的状态,更新对应状态下的Drawable对象。

d.setState(getDrawableState());

}

}

/*Return an array of resource IDs of the drawable states representing the

  • current state of the view.

*/

public final int[] getDrawableState() {

if ((mDrawableState != null) && ((mPrivateFlags & DRAWABLE_STATE_DIRTY) == 0)) {

return mDrawableState;

} else {

//根据当前View的状态属性值,将其转换为一个整型集合,并返回

mDrawableState = onCreateDrawableState(0);

mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;

return mDrawableState;

}

}

通过这段代码我们可以明白View内部是如何获取更细后的状态值以及动态获取对应的背景Drawable对象----setState()方法

去完成的。这儿我简单的分析下Drawable类里的setState()方法的功能,把流程给走一下:

Step 1 、 setState()函数原型 ,

函数位于:frameworks\base\graphics\java\android\graphics\drawable\StateListDrawable.java 类中

//如果状态态值发生了改变,就回调onStateChange()方法。

public boolean setState(final int[] stateSet) {

if (!Arrays.equals(mStateSet, stateSet)) {

mStateSet = stateSet;

return onStateChange(stateSet);

}

return false;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值