-
//没有任何状态时显示的图片,我们给它设置我空集合
-
stalistDrawable.addState(new int []{}, getResources().getDrawable(R.drawable.pic5);
上面的“-”负号表示对应的属性值为false
当我们为某个View使用其作为背景色时,会根据状态进行背景图的转换。
public boolean isStateful ()
功能: 表明该状态改变了,对应的drawable图片是否会改变。
注:在StateListDrawable类中,该方法返回为true,显然状态改变后,我们的图片会跟着改变。
知识点二:View的五种状态值
一般来说,Android框架为View定义了四种不同的状态,这些状态值的改变会引发View相关操作,例如:更换背景图片、是否
触发点击事件等;视
视图几种不同状态含义见下图:
其中selected和focused的区别有如下几点:
1,我们通过查看setSelected()方法,来获取相关信息。
SDK中对setSelected()方法----对于与selected状态有如下说明:
public void setSelected (boolean selected)
Since: APILevel 1
Changes the selection state of this view. Aview 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处于高亮状态。
2、一个窗口只能有一个视图获得焦点(focus),而一个窗口可以有多个视图处于”selected”状态中。
总结:focused状态一般是由按键操作引起的;
pressed状态是由触摸消息引起的;
selected则完全是由应用程序主动调用setSelected()进行控制。
例如:当我们触摸某个控件时,会导致pressed状态改变;获得焦点时,会导致focus状态变化。于是,我们可以通过这种
更新后状态值去更新我们对应的Drawable对象了。
问题:如何根据状态值的改变去绘制/显示对应的背景图?
当View任何状态值发生改变时,都会调用refreshDrawableList()方法去更新对应的背景Drawable对象。
其整体调用流程如下: View.java类中
[java] view plain copy print ?
-
//路径:\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(g