gpt4 book ai didi

java - Android onFocusChanged 函数从未被调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:52:18 26 4
gpt4 key购买 nike

我已经按照本教程中的说明在扩展 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);
}
}
...
}

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

那么,我是不是忘记了一步?还有什么我错过的吗?

最佳答案

事实上,问题在于我没有将自定义按钮的属性“在触摸模式下可聚焦”设置为 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);
}
...
}

关于java - Android onFocusChanged 函数从未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6886083/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com