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 ?
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);
}
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With