【问题标题】:Is there any way to Detect userInterations in Android fragments?有什么方法可以检测 Android 片段中的 userInterations 吗?
【发布时间】:2017-04-12 01:13:43
【问题描述】:

任何人都可以帮助我解决这种情况。

我已经为 Android Activity 实现了OnUserInteraction() 方法,它对我来说工作正常。

但我也想要Fragments。我怎样才能调用OnUserInteraction(),或者有没有其他方法可以用UI 识别userInteraction

【问题讨论】:

  • 目前尚不清楚您要达到的目标。请editminimal reproducible example
  • 如果我的应用程序处于空闲模式(后台和前台),我想关闭它。OnUserInteraction 正在为我工​​作,但我无法在片段中实现它。
  • Fragment 保存在 Activity 中。我不明白你为什么认为你需要在那里实现该方法。

标签: android android-fragments user-interaction


【解决方案1】:

还有另一种方法。

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

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();
}

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

((YourActivity) getActivity()).setUserInteractionListener(new YourActivity.UserInteractionListener() {
    @Override
    public void onUserInteraction() {
        // Do whatever you want here, during user interaction
    }
});

【讨论】:

  • onUserInteraction () 中的方法没有被调用
  • @ClaudeHangui 哪个 onUserInteraction() 没有被调用? Activity 的重写方法还是来自匿名内部类 YourActivity.UserInteractionListener 的方法?
  • 我正在尝试在微调器上实现此解决方法。所以我按照上面所示的步骤,在我的片段中注册了事件,但是点击微调器似乎不起作用,即它没有执行预期的行为
【解决方案2】:

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

最后一部分很重要。

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 2021-12-25
    相关资源
    最近更新 更多