任何人都可以解释何时准确调用View.drawableStateChanged吗?我想将其与ViewGroup.setAddStatesFromChildren结合使用以使完整的ViewGroup
“光学”聚焦,例如更改背景颜色,例如此EditText
的ViewGroup
获得焦点。
当我实现View.drawableStateChanged
时,它经常被调用,我怎么知道当前的调用是我所关心的?与将侦听器集中在子视图上相比,有什么优势?
您可以详细了解here。
[只要视图状态改变一种影响显示的可绘制状态的方式。
如果创建像这样的可绘制对象:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/>
<item android:state_focused="true"
android:color="#ff0000ff"/>
<item android:state_enabled="true"
android:color="#ff00ffff"/>
<item android:color="#ff000000"/>
</selector>
此drawable主要具有三个状态(state_pressed,state_focused,state_enabled)。如果已将可绘制设置为特定视图,并且该视图是可单击的,则单击该视图时,此状态通常会更改。
您可以使用setOnFocusChangeListener
检查焦点变化和setOnTouchListener
触摸事件。另外,您可以检查以启用/禁用该视图的状态onClick()
事件。
为简单起见,您希望整个Viewgroup
都集中在它的一个子对象实际上是因为您只需要ViewGroup.setAddStatesFromChildren
创建一个drawable
文件,在我的代码中将其称为view_focus:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_focused="true">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
<corners android:radius="19dp"/>
<stroke android:color="@color/green" android:width="2dp"/>
</shape>
</item>
<item android:state_enabled="true" android:state_focused="false">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
<corners android:radius="19dp"/>
<stroke android:color="@color/black" android:width="2dp"/>
</shape>
</item>
</selector>
现在在您的[[活动布局中,您必须像下面这样在视图组及其子级中将上面的可绘制对象作为背景传递:
<RelativeLayout
android:background="@drawable/view_focus"
android:layout_centerInParent="true"
android:id="@+id/parentlayout"
android:layout_width="300dp"
android:layout_height="250dp">
<EditText
android:padding="5dp"
android:textSize="20sp"
android:layout_centerInParent="true"
android:background="@drawable/view_focus"
android:id="@+id/edit"
android:layout_width="200dp"
android:layout_height="wrap_content"/>
<EditText
android:padding="5dp"
android:textSize="20sp"
android:layout_centerInParent="true"
android:background="@drawable/view_focus"
android:layout_below="@+id/edit"
android:layout_marginTop="20dp"
android:layout_width="200dp"
android:layout_height="wrap_content"/>
</RelativeLayout>
在这种情况下,RelativeLayout
的父布局是Viewgroup
,它的子代是两个EditText
,如果您执行此代码,则一旦单击,只有子代会获得Focus
,如果您希望整个ViewGroup获得,请关注在活动类文件中添加以下行:
relativeLayout = findViewById(R.id.parentlayout); relativeLayout.setAddStatesFromChildren(true);
这是使用上一行后的结果。以及使用
ViewGroup.setAddStatesFromChildren
之前的内容
This function is called whenever the state of the view changes in
such a way that it impacts the state of drawables being shown.
似乎每当需要重绘组件时,框架都会调用此函数,您可以重写它以(例如)执行,以便在重绘组件时需要执行特定于应用程序的逻辑,例如手动绘制某些东西在组件顶部,或者更改字体或执行一些无法使用stock属性进行的操作。This question有一个如何实现它的示例。