Issue
Can anyone explain when exactly View.drawableStateChanged is called? I want to use it in conjunction with ViewGroup.setAddStatesFromChildren to make a complete ViewGroup "optically" focused, meaning e.g. change background color when e.g. an EditText of this ViewGroup gets focus.
When I implement View.drawableStateChanged it's called very often, how do I know that the current call is the one I care about? What's the advantage over settings focus listeners on the child Views?
Solution
to make it simple, you want your whole Viewgroup be focused when one of its children is actually focused for that you only need ViewGroup.setAddStatesFromChildren
create a drawable file i call it view_focus in my code :
<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>
now in your activity layout you have to pass the above drawable as a background both in your Viewgroup and its children like the following :
<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>
in this case RelativeLayout parentlayout is the Viewgroup and it's children are the two EditText if you execute this code only the children will gain Focus once clicked, if you want your whole ViewGroup gain Focus your need to add this line in your Activity Class file :
relativeLayout = findViewById(R.id.parentlayout);
relativeLayout.setAddStatesFromChildren(true);
this is the result after using the above line.

and this before using ViewGroup.setAddStatesFromChildren

Answered By - Khalil Snoussi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.