Android - 从成员类控制活动
首先,我是 Android 编程的新手,我有一些 Java 基础,我查看了 SO 并用 google 搜索了我的问题,但没有匹配。 我一直在尝试让以下教程工作几个小时。该项目由两个类组成:一个 Activity 和一个扩展 SimpleOnGestureListener
的 SwipeDetector 类。
摩托罗拉网站提供的解决方案有效,但当我尝试在检测到向左或向右滑动时“修改”活动时遇到了麻烦。为了测试它,我预计在滑动时会显示一些 Toast。
我的“解决方案”是为 SwipeDetector 创建一个构造函数,它将调用 Activity
的 ActivityClass
和 Context
作为参数。知道这些信息后,可以轻松调用 mParent.moveScreenRight();
,其中 mParent 是父 Activity。
我知道这个解决方案看起来很糟糕,我希望我能在这里得到一些建议。如果需要,我可以提供有关这两个类实现的更多信息。
谢谢 !
问候, 杰罗姆
First, I'm quite beginner to Android programming, I got some basis in Java and I looked on SO and googled my problem with no match.
I've been trying to make the following tutorial work for several hours. The project is composed of two classes : an activity and a class SwipeDetector which extends SimpleOnGestureListener
.
The solution offered by Motorola website works but I got trouble when I tried to "modify" the activity when left or right swipe is detected. To test it, I expected some Toasts to show when swiping.
My "solution" was to create a constructor for SwipeDetector which takes as parameters the ActivityClass
and Context
of calling Activity
. When these informations are known it's easye to call mParent.moveScreenRight();
where mParent is the parent Activity.
I'm aware that this solution seems awful, and I hope I could get some advices here. I can provide more information about the two classes impletentations if needed.
Thanks !
Regards,
Jerome
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从您的描述中并不清楚问题是什么,但是从字里行间阅读并查看教程,我认为您缺少的是教程中的 SwipeDetector 是 Activity 的内部类。这是它调用
moveScreenRight()
或moveSreenLeft()
的唯一方法,它们调用 Activity 类的mFlipper
成员。因此,代码应该类似于“
除了将 SwipeDetector 设为内部类之外,实际上无法避免传递对其构造函数的引用以启用对 Activity 的调用方法”。抽象出来的最简洁的方法是使用 Joseph Earl 建议的接口解决方案。
It's not clear from your description exactly what the problem is, but reading between the lines and looking at the tutorial, I think what you're missing is that the SwipeDetector in the tutorial is an inner class of the Activity. That's the only way it could call
moveScreenRight()
ormoveSreenLeft()
, which call themFlipper
member of the Activity class.So the code should look something like
Short of making SwipeDetector an inner class, there's really no avoiding passing a reference to its constructor to enable calling methods on the Activity. The cleanest way to abstract that away is with the interface solution suggested by Joseph Earl.
您始终可以让手势检测器采用接口,以便您可以传递不同的活动。
然后在您的实际活动中
实现
MovableActivity然后您的滑动检测器的构造函数可以采用
MovableActivity
并调用moveLeft
和moveRight
关于这一点。You could always make your Gesture detector take an interface so you can pass in different activities.
Then in your actual activity
implement
MovableActivityThen your constructor for the swipe detector can take a
MovableActivity
and callmoveLeft
andmoveRight
on that.