@Sunil 的回答导致 java.lang.StackOverflowError 所以我纠正了它。下面的代码运行顺利
在您的应用程序中创建一个名为 UserInterationListener 的 java 类,并将下面的代码放在那里
public interface UserInteractionListener {
void onUserInteraction();
}
然后在你的activity中创建一个实例变量,这个接口如下
private UserInteractionListener userInteractionListener;
然后在你的活动中为这个变量实现一个 setter 方法。
public void setUserInteractionListener(UserInteractionListener userInteractionListener) {
this.userInteractionListener = userInteractionListener;
}
现在覆盖您的活动的 onUserInteraction 方法,如果侦听器变量不为空,则调用接口方法。
@Override
public void onUserInteraction() {
super.onUserInteraction();
if (userInteractionListener != null)
userInteractionListener.onUserInteraction();
}
现在,在您的片段类中,如下实现 UserInteractionListener
public myFragment extends Fragment implements UserInteractionListener
也覆盖接口的方法
@Override
public void onUserInteraction(){
//TODO://do your work on user interaction
}
然后在您的片段中调用您的活动的用户交互设置方法,如下所示
((YourActivity) getActivity()).setUserInteractionListener(this);
最后一部分很重要。