Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding View.drawableStateChanged

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?

like image 567
stefan.at.wpf Avatar asked Dec 01 '25 02:12

stefan.at.wpf


1 Answers

You can learn more about it here.

View.drawableStateChanged() is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

If you create drawable like this:

<?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>

This drawable has mainly different states(like state_pressed, state_focused, state_enabled). If you have set drawable to a particular view and that view is clickable then when you click on of that view, this state generally changes.

You can use setOnFocusChangeListener to check about focus changes and setOnTouchListener touch events. Also, you can check to enable/disable the state onClick() event of that view.

Update: This method is deprecated, please follow this link for more.

like image 111
realpranav Avatar answered Dec 02 '25 15:12

realpranav