[英]How to check if a particular view is currently focussed in Android
In my android app I need to check whether a particular view is focussed. 在我的android应用中,我需要检查特定视图是否聚焦。 Now I found the getCurrentFocus() function in Activity class but this returns a View Object.
现在,我在Activity类中找到了getCurrentFocus()函数,但这返回了一个View Object。
How can I compare and check whether this returned View is same as the one in question. 如何比较并检查此返回的View是否与所讨论的View相同。 I mean there is no getName() function here.
我的意思是这里没有getName()函数。 So after getting the View object, how can I compare to check which View class is this ?
因此,在获取View对象之后,如何比较这是哪个View类?
The View.isFocused()
method tells whether the view in question is focused or not. View.isFocused()
方法告知所关注的视图是否已聚焦。
if (myView.isFocused()) {
// your code
}
If you still want to use the getCurrentFocus() method, you can simply check: 如果仍然要使用getCurrentFocus()方法,则可以简单地检查:
View focusView = getCurrentFocus();
if (myView == focusView) {
// your code
}
Or else, you can compare your views by id. 否则,您可以按ID比较您的观看次数。
View focusView = getCurrentFocus();
if (focusView != null && myView.getId() == focusView.getId()) {
// your code
}
You could use the getId() method I guess? 我猜你可以使用getId()方法吗?
eg 例如
getCurrentFocus() == R.id.myView;
getCurrentFocus() on the parent view 父视图上的getCurrentFocus()
http://developer.android.com/reference/android/app/Activity.html#getCurrentFocus%28%29 http://developer.android.com/reference/android/app/Activity.html#getCurrentFocus%28%29
No need for getName(). 不需要getName()。 Just use the == operator.
只需使用==运算符。 See:
看到:
View myView = findViewById(...);
if (activitygetCurrentFocus() == myView)
// ha focus
}
Another option, one I usually prefer, is to set a focus listener for the views you are interested in monitoring: 我通常更喜欢的另一种选择是为您想要监视的视图设置焦点侦听器:
myView.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// got focus logic
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.