Android View的五种状态值

参考 http://blog.csdn.net/qinjuning/article/details/7474827

Android 框架对View定义了五中不同的状态,这些状态会引发View不同的相关操作。

Android View的五种状态值_第1张图片

selected状态

SDK的解释

public void setSelected (boolean selected)
Since: APILevel 1
Changes the selection state of this view. A view can be selected or not. Note that selection is not the same as focus. Views are typically selected in the context of an AdapterView like ListView or GridView ;the selected view is the view that is highlighted.
Parameters selected true if the view must be selected, false otherwise

由以上可知:selected不同于focus状态,通常在AdapterView类群下例如ListView或者GridView会使某个View处于selected状态,并且获得该状态的View处于高亮状态。

focused状态

与selected的不同

一个窗口中,只能有一个View处于focused状态,但是可以有多个View处于selected状态

  • focused状态一般是由按键操作引起的;

  • pressed状态是由触摸消息引起的;

  • selected则完全是由应用程序主动调用setSelected()进行控制。

 Android View 根据状态值,重新绘制背景

//路径:\frameworks\base\core\java\android\view\View.java  
/* 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;  
    }  
}  

selector标签的各状态值的使用

     
<selector xmlns:android="http://schemas.android.com/apk/res/android">   
      
  <item android:state_pressed="true" android:state_window_focused="true" android:drawable= "@drawable/pic1" />  
      
  <item android:state_pressed="true" android:state_focused="false" android:drawable="@drawable/pic2" />    
      
  <item android:state_selected="true" android:drawable="@drawable/pic3" />     
      
  <item android:state_focused="true" android:drawable="@drawable/pic4" />    
      
  <item android:drawable="@drawable/pic5" />   
selector>  

你可能感兴趣的:(android)