开发者

Android - Control an activity from member class

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 开发者_如何学JAVAthe 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


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() or moveSreenLeft(), which call the mFlipper member of the Activity class.

So the code should look something like

public class MyActivity extends Activity {

  // All the Activity overrides elided

  class SwipeDetector extends SimpleGestureListener {

    // all the SwipeDetector methods
  }
}

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.


You could always make your Gesture detector take an interface so you can pass in different activities.

interface MovableActivity {

    public void moveLeft();
    public void moveRight();
}

Then in your actual activity implement MovableActivity

class MyActivity extends Activity implements MovableActivity { ...

Then your constructor for the swipe detector can take a MovableActivity and call moveLeft and moveRight on that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜