Android onFocusChanged函数从未调用过

Ced*_*sme 6 java android

我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);
        }
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

事实上,当我点击我的自定义按钮时没有任何反应......使用调试器,我可以看到函数永远不会被调用.我不知道为什么.

那么,我忘记了一步吗?还有其他我错过的东西吗?

Ced*_*sme 7

事实上,问题是我没有将我的自定义按钮的属性"在触摸模式下可聚焦"设置为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);  
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)


Phi*_*hil 0

文档说“覆盖时,请务必调用超类,以便进行标准焦点处理。” 您在上面的代码中省略了该调用,如下所示的内容应该有所帮助。

@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);  
}
Run Code Online (Sandbox Code Playgroud)