Android中View(视图)绘制不同状态背景图片原理深入分析以及StateListDrawable使用详解

本文深入解析Android中View如何根据状态切换背景图片,详细阐述`refreshDrawableState()`、`drawableStateChanged()`等关键方法的运作机制,并通过StateListDrawable的`setState()`方法展示状态匹配逻辑。此外,还介绍了Drawable.Callback接口的角色,以及View的绘制流程。最后,通过一个Demo演示如何自定义View实现类似功能。
摘要由CSDN通过智能技术生成
  1. //路径:\frameworks\base\core\java\android\view\View.java

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

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

  4. * in the new state should call getDrawableState.

  5. */

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

  7. public void refreshDrawableState() {

  8. mPrivateFlags |= DRAWABLE_STATE_DIRTY;

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

  10. drawableStateChanged();

  11. }

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

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

  14. */

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

  16. protected void drawableStateChanged() {

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

  18. Drawable d = mBGDrawable;

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

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

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

  22. d.setState(getDrawableState());

  23. }

  24. }

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

  26. * current state of the view.

  27. */

  28. public final int[] getDrawableState() {

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

  30. return mDrawableState;

  31. } else {

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

  33. mDrawableState = onCreateDrawableState(0);

  34. mPrivateFlags &= ~DRAWABLE_STATE_DIRTY;

  35. return mDrawableState;

  36. }

  37. }

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

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

Step 1 、 setState()函数原型 ,

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

[java]  view plain copy print ?

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

  2. public boolean setState(final int[] stateSet) {

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

  4. mStateSet = stateSet;

  5. return

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值