Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android onFocusChanged function never called

Tags:

java

android

I have created a custom button in extending View class as specified in this tutorial:

http://kahdev.wordpress.com/2008/09/13/making-a-custom-android-button-using-a-custom-view/

But I have a problem with the function onFocusChanged() which is never called.

This is my code:

public class CustomButton extends View
{
    ...
    public CustomButton(Context context, Car car) 
    {
        super(context);
        setFocusable(true);
        setBackgroundColor(Color.BLACK);
        setOnClickListener(listenerAdapter);
        setClickable(true);
    }

    @Override
    protected void onFocusChanged(boolean gainFocus, int direction,
                                  Rect previouslyFocusedRect)
    {
        if (gainFocus == true)
        {
            this.setBackgroundColor(Color.rgb(255, 165, 0));
        }
        else
        {
            this.setBackgroundColor(Color.BLACK);
        }
    }
    ...
}

In fact, when I click on my custom button nothing happens... With the debugger, I can see that the function is never called. And I don't know why.

So, had I forgotten a step ? Is there another thing I have missed ?

like image 358
Cedekasme Avatar asked Jul 30 '11 21:07

Cedekasme


1 Answers

In fact, the problem was that I haven't set the property "focusable in touch mode" of my custom button to true. I have added in the constructor setFocusableInTouchMode(true); and it works better. Thank you Phil and Vicki D for your help.

public class CustomButton extends View
{
    ...
    public CustomButton(Context context, Car car) 
    {
        super(context);
        setFocusable(true);
        setFocusableInTouchMode(true); // Needed to call onFocusChanged()
        setBackgroundColor(Color.BLACK);
        setOnClickListener(listenerAdapter);
        setClickable(true);
    }

    @Override
    protected void onFocusChanged(boolean gainFocus, int direction,
                                  Rect previouslyFocusedRect)
    {
        if (gainFocus == true)
        {
            this.setBackgroundColor(Color.rgb(255, 165, 0));
        }
        else
        {
            this.setBackgroundColor(Color.BLACK);
        }
        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);  
    }
    ...
}
like image 175
Cedekasme Avatar answered Nov 09 '22 23:11

Cedekasme