有什么方法可以检测Android片段中的userInterations? [英] Is there any way to Detect userInterations in Android fragments?
问题描述
有人能帮助我解决这种情况吗?
Could any one help me out with this situation.
我已经为Android Activity实现了 OnUserInteraction()
方法,对我来说效果很好.
I have implemented OnUserInteraction()
method for Android Activity it is working fine for me.
但是我也想将其用于 Fragments
.如何调用 OnUserInteraction()
或还有其他方法来标识 userInteraction
UI
.
But I want it for Fragments
too.How can i able call OnUserInteraction()
or is there any another way to identify userInteraction
with the UI
.
推荐答案
@Sunil的答案会导致java.lang.StackOverflowError,因此我进行了更正.下面的代码运行顺利
@Sunil's answer causes java.lang.StackOverflowError so I corrected it. Below code works smoothly
在您的应用中创建一个名为UserInterationListener的Java类,并在下面放置代码
Create a java class in your app named UserInterationListener and put below code there
public interface UserInteractionListener {
void onUserInteraction();
}
然后在您的活动中为此界面创建一个实例变量,如下所示
Then create an instance variable in your activity, for this interface as below
private UserInteractionListener userInteractionListener;
然后在您的活动中为该变量实现一个setter方法.
Then implement a setter method for this variable, in your activity.
public void setUserInteractionListener(UserInteractionListener userInteractionListener) {
this.userInteractionListener = userInteractionListener;
}
现在覆盖您活动的onUserInteraction方法,如果listener变量不为null,则调用接口方法.
Now override the onUserInteraction method of your activity and if the listener variable is not null, invoke the interface method.
@Override
public void onUserInteraction() {
super.onUserInteraction();
if (userInteractionListener != null)
userInteractionListener.onUserInteraction();
}
现在,在您的片段类中,如下实现UserInteractionListener
Now, in your fragment class, implement UserInteractionListener as below
public myFragment extends Fragment implements UserInteractionListener
还覆盖接口的方法
@Override
public void onUserInteraction(){
//TODO://do your work on user interaction
}
然后在您的片段中调用活动的userinteraction setter方法,如下所示
then in your fragment invoke your activity's userinteraction setter method like below
((YourActivity) getActivity()).setUserInteractionListener(this);
这最后一部分很重要.
这篇关于有什么方法可以检测Android片段中的userInterations?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!