有什么方法可以检测Android片段中的用户交互吗?

问题描述 投票:0回答:3

任何人都可以帮我解决这种情况吗?

我已经为 Android Activity 实现了

OnUserInteraction()
方法,它对我来说工作得很好。

但是我也想要

Fragments
。我怎样才能打电话给
OnUserInteraction()
或者有没有其他方法可以将
userInteraction
UI
识别。

android android-fragments user-interaction
3个回答
2
投票

@Sunil 的回答导致 java.lang.StackOverflowError 所以我更正了它。下面的代码运行顺利

在您的应用程序中创建一个名为 UserInterationListener 的 java 类,并将以下代码放在那里

public interface UserInteractionListener {
    void onUserInteraction();
}

然后在您的活动中创建一个实例变量,如下所示

private UserInteractionListener userInteractionListener;

然后在您的活动中为此变量实现一个 setter 方法。

public void setUserInteractionListener(UserInteractionListener userInteractionListener) {
    this.userInteractionListener = userInteractionListener;
}

现在重写 Activity 的 onUserInteraction 方法,如果侦听器变量不为 null,则调用接口方法。

@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);

最后一部分很重要。


0
投票

最简单的方法是在 onViewCreated 中实现触摸监听器,如下所示

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    view.setOnTouchListener { v, event ->
        requireActivity().onUserInteraction()
        true
    }
}

顺便说一句,这个解决方案是用 Kotlin 实现的


-1
投票

还有另一种方法。

在您的活动中创建一个侦听器,如下所示

public interface UserInteractionListener {
    void onUserInteraction();
}

然后在您的活动中创建一个实例变量,如下所示

private UserInteractionListener userInteractionListener;

然后在您的活动中为此变量实现一个 setter 方法。 (如果您想将相同的用户交互传递给多个消费者,您甚至可以保留事件侦听器对象的列表)

public void setUserInteractionListener(UserInteractionListener userInteractionListener) {
    this.userInteractionListener = userInteractionListener;
}

现在重写 Activity 的

onUserInteraction
方法,如果侦听器变量不为 null,则调用接口方法。

@Override
public void onUserInteraction() {
    super.onUserInteraction();
    if (userInteractionListener != null)
        userInteractionListener.onUserInteraction();
}

现在,在您的片段类中,注册事件如下

((YourActivity) getActivity()).setUserInteractionListener(new YourActivity.UserInteractionListener() {
    @Override
    public void onUserInteraction() {
        // Do whatever you want here, during user interaction
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.