Android的onFocusChanged函数从未被调用



我已经创建了一个自定义按钮来扩展本教程中指定的View类:

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

但我有一个问题与功能onFocusChanged()从未被调用。

这是我的代码:

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

事实上,当我点击我的自定义按钮什么都没有发生…使用调试器,我可以看到该函数从未被调用。我不知道为什么。

那么,我忘记了一个步骤吗?

事实上,问题在于我没有将自定义按钮的属性"focusable In touch mode"设置为true。我在构造器setFocusableInTouchMode(true);中添加了它,它的工作效果更好。谢谢Phil和Vicki 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);  
    }
    ...
}

文档说"当重写时,一定要调用到超类,这样标准的焦点处理才会发生。"你在上面的代码中省略了这个调用,下面的代码应该会有所帮助。

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

必须在构造函数中使用setOnFocusChangeListener。像这样:

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

最新更新