Android function onFocusChanged never called

I created a custom button in the class extension View, as indicated 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 a function onFocusChanged()that 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 see that the function is never called. And I do not know why.

So, if I forgot the step? Is there another thing that I missed?

+5
source share
3 answers

, "focusable in touch mode" true. setFocusableInTouchMode(true);, . , D .

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);  
    }
    ...
}
+6

: " , ". , - .

@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);  
}
0

you should setOnFocusChangeListenerin your constructor. something like that:

 public CustomButton(Context context, Car car) 
{
    ...
    setOnFocusChangeListener(this);
    ...
}
0
source

All Articles