如何检查特定视图当前是否集中在Android中

如何检查特定视图当前是否集中在Android中,android,view,Android,View,在我的android应用程序中 我需要检查一个特定的视图是否聚焦。 现在我在Activity类中找到了getCurrentFocus()函数 但这将返回一个视图对象 如何比较和检查此返回的视图是否与所讨论的视图相同。 我的意思是这里没有getName()函数。 因此,在获取视图对象后,如何比较以检查这是哪个视图类?方法告诉我们所讨论的视图是否聚焦 if (myView.isFocused()) { // your code } 如果仍要使用getCurrentFocus()方法,只需检

在我的android应用程序中 我需要检查一个特定的视图是否聚焦。 现在我在Activity类中找到了getCurrentFocus()函数 但这将返回一个视图对象

如何比较和检查此返回的视图是否与所讨论的视图相同。 我的意思是这里没有getName()函数。 因此,在获取视图对象后,如何比较以检查这是哪个视图类?

方法告诉我们所讨论的视图是否聚焦

if (myView.isFocused()) {
    // your code
}
如果仍要使用getCurrentFocus()方法,只需检查:

View focusView = getCurrentFocus();
if (myView == focusView) {
    // your code
}
或者,您可以按id比较视图

View focusView = getCurrentFocus();
if (focusView != null && myView.getId() == focusView.getId()) {
    // your code
}
View.isFocused()
方法告诉您所讨论的视图是否聚焦

if (myView.isFocused()) {
    // your code
}
如果仍要使用getCurrentFocus()方法,只需检查:

View focusView = getCurrentFocus();
if (myView == focusView) {
    // your code
}
或者,您可以按id比较视图

View focusView = getCurrentFocus();
if (focusView != null && myView.getId() == focusView.getId()) {
    // your code
}
我想您可以使用getId()方法

e、 g

我想您可以使用getId()方法

e、 g

父视图上的getCurrentFocus()

父视图上的getCurrentFocus()

不需要getName()。只需使用==运算符。见:

View myView = findViewById(...);

if (activitygetCurrentFocus() == myView)
    // ha focus

}
另一个选项(我通常更喜欢)是为您感兴趣监视的视图设置焦点侦听器:

myView.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
          if (hasFocus) {
               // got focus logic
          }
    }
});
不需要getName()。只需使用==运算符。见:

View myView = findViewById(...);

if (activitygetCurrentFocus() == myView)
    // ha focus

}
另一个选项(我通常更喜欢)是为您感兴趣监视的视图设置焦点侦听器:

myView.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
          if (hasFocus) {
               // got focus logic
          }
    }
});

您可以使用视图的
hasFocus()
。您只需要使用此方法检查每个可聚焦视图。您可以使用视图的
hasFocus()
。您只需要使用这个method.Works检查每个可聚焦视图,但我得到的方法调用getId可能会产生javaNullpointerException@CGR好吧,isFocused()是这里的首选方式。getCurrentFocus()可以返回空视图,因此如果决定使用getId(),则应首先执行空检查。更新的答案可执行空检查。谢谢@CGR.Works,但我得到的方法调用getId可能会产生javaNullpointerException@CGR好吧,isFocused()是这里的首选方式。getCurrentFocus()可以返回空视图,因此如果决定使用getId(),则应首先执行空检查。更新的答案可执行空检查。谢谢@CGR。